Zibbobz Zibbobz - 9 months ago 61
Java Question

How do I convert a StringReader to a String?

I'm trying to convert my

back to a regular
, as shown:

String string = reader.toString();

But when I try to read this string out, like this:

System.out.println("string: "+string);

All I get is a pointer value, like this:


Am I doing something wrong in reading the string back?

Answer Source

The StringReader's toString method does not return the StringReader internal buffers.

You'll need to read from the StringReader to get this.

I recommend using the overload of read which accepts a character array. Bulk reads are faster than single character reads.


//use string builder to avoid unnecessary string creation.
StringBuilder builder = new StringBuilder();
int charsRead = -1;
char[] chars = new char[100];
    charsRead = reader.read(chars,0,chars.length);
    //if we have valid chars, append them to end of string.
String stringReadFromReader = builder.toString();
System.out.println("String read = "+stringReadFromReader);