How do I convert a StringReader to a String?
Solution 1
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);
Solution 2
import org.apache.commons.io.IOUtils;
String string = IOUtils.toString(reader);
Solution 3
Or using CharStreams
from Googles Guava library:
CharStreams.toString(stringReader);
Solution 4
If you prefer not to use external libraries:
Scanner scanner = new Scanner(reader).useDelimiter("\\A");
String str = scanner.hasNext() ? scanner.next() : "";
The reason for the hasNext()
check is that next()
explodes with a NoSuchElementException
if the reader wraps a blank (zero-length) string.
Solution 5
Another native (Java 8+) solution could be to pass the StringReader
object to a BufferedReader
and stream trough the lines:
try (BufferedReader br = new BufferedReader(stringReader)) {
br.lines().forEach(System.out::println);
}
Related videos on Youtube
Comments
-
Zibbobz almost 2 years
I'm trying to convert my
StringReader
back to a regularString
, 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?
-
Matt Ball almost 11 yearsClearly, you are. docs.oracle.com/javase/7/docs/api/java/io/StringReader.html
-
nanofarad almost 11 yearsYou can't get the string back from a stringreader without using read(.
-
-
William Morrison almost 11 yearsA bulk read with an array will be faster than reading a single character at a time.