Java – how to convert a stringreader to a string?
•
Java
I'm trying to convert my stringreader back to a regular string, as shown in the figure:
String string = reader.toString();
But when I try to read this string, it's like this:
System.out.println("string: "+string);
What I get is a pointer value, as follows:
java.io.StringReader@2c552c55
Did I make a mistake reading the string?
Solution
The toString method of stringreader does not return the internal buffer of stringreader
You need to read this from stringreader
I recommend using an overload of read that accepts character arrays Batch reading speed is higher than single character reading
Namely
//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,chars.length); //if we have valid chars,append them to end of string. if(charsRead>0) builder.append(chars,charsRead); }while(charsRead>0); String stringReadFromReader = builder.toString(); System.out.println("String read = "+stringReadFromReader);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码