How do I convert a StringReader to a String?

2020-02-09 07:31发布

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?

9条回答
\"骚年 ilove
2楼-- · 2020-02-09 07:35
import org.apache.commons.io.IOUtils;

String string = IOUtils.toString(reader);
查看更多
走好不送
3楼-- · 2020-02-09 07:41

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);
查看更多
forever°为你锁心
4楼-- · 2020-02-09 07:41

You're printing out the toString() of the actual StringReader object, NOT the contents of the String that the StringReader is reading.

You need to use the read() and/or the read(char[] cbuf, int off, int len) methods to read the actual chars in the String.

查看更多
我命由我不由天
5楼-- · 2020-02-09 07:42

Or using CharStreams from Googles Guava library:

CharStreams.toString(stringReader);
查看更多
姐就是有狂的资本
6楼-- · 2020-02-09 07:47

If you use the method toString() in a StringReader object you will print the memory position of the object. You have yo use one of this method:

read() Reads a single character.

read(char[] cbuf, int off, int len) Reads characters into a portion of an array.

Here an example:

     String s = "Hello World";

    // create a new StringReader
    StringReader sr = new StringReader(s);

    try {
        // read the first five chars
        for (int i = 0; i < s.length(); i++) {
            char c = (char) sr.read();
            System.out.print("" + c);
        }

        // close the stream
        sr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
查看更多
做自己的国王
7楼-- · 2020-02-09 07:56

reader.toString(); will give you the results of calling the generic toString() method from Object class.

You can use the read() method:

int i;               
do {
    i = reader.read();
    char c = (char) i;
    // do whatever you want with the char here...

} while (i != -1);   
查看更多
登录 后发表回答