Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a StringReader to a String?

Tags:

I'm trying to convert my StringReader back to a regular String, 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:

java.io.StringReader@2c552c55 

Am I doing something wrong in reading the string back?

like image 205
Zibbobz Avatar asked Jul 19 '13 16:07

Zibbobz


People also ask

How do I turn a char variable into a String?

We can convert a char to a string object in java by using the Character. toString() method.

Can StringBuilder be converted to String?

To convert a StringBuilder to String value simple invoke the toString() method on it. Instantiate the StringBuilder class. Append data to it using the append() method. Convert the StringBuilder to string using the toString() method.


2 Answers

import org.apache.commons.io.IOUtils;  String string = IOUtils.toString(reader); 
like image 104
ottago Avatar answered Oct 22 '22 08:10

ottago


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.

ie.

//use string builder to avoid unnecessary string creation. StringBuilder builder = new StringBuilder(); int charsRead = -1; char[] chars = new char[100]; do{     charsRead = reader.read(chars,0,chars.length);     //if we have valid chars, append them to end of string.     if(charsRead>0)         builder.append(chars,0,charsRead); }while(charsRead>0); String stringReadFromReader = builder.toString(); System.out.println("String read = "+stringReadFromReader); 
like image 20
William Morrison Avatar answered Oct 22 '22 06:10

William Morrison