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条回答
孤傲高冷的网名
2楼-- · 2020-02-09 07:56

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);
}
查看更多
Fickle 薄情
3楼-- · 2020-02-09 07:57

Calling toString() method will give the object of StringReader class. If yo want it's content then you need to call the read method on StringReader like this:

public class StringReaderExample {

   public static void main(String[] args) {

      String s = "Hello World";

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

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

         // close the stream
         sr.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

For tutorials you can use this link.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-09 07:58

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.

查看更多
登录 后发表回答