How do I convert a StringReader to a String?
Asked Answered
G

10

21

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?

Gelding answered 19/7, 2013 at 16:26 Comment(2)
Clearly, you are. docs.oracle.com/javase/7/docs/api/java/io/StringReader.htmlOnym
You can't get the string back from a stringreader without using read(.Avertin
K
11

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);
Kyanite answered 19/7, 2013 at 16:29 Comment(1)
See @Kiran's answer for a Java 9+ solution that is much simpler.Rentroll
T
27
import org.apache.commons.io.IOUtils;

String string = IOUtils.toString(reader);
Tiflis answered 27/10, 2014 at 5:38 Comment(1)
See @Kiran's answer for a Java 9+ solution that does not use external libraries.Rentroll
K
11

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);
Kyanite answered 19/7, 2013 at 16:29 Comment(1)
See @Kiran's answer for a Java 9+ solution that is much simpler.Rentroll
C
5

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.

Cancroid answered 30/11, 2016 at 23:50 Comment(0)
T
4

Or using CharStreams from Googles Guava library:

CharStreams.toString(stringReader);
Theaterintheround answered 11/1, 2016 at 10:21 Comment(1)
See @Kiran's answer for a Java 9+ solution that does not use external libraries.Rentroll
C
2

As per https://www.tutorialspoint.com/java/io/stringwriter_tostring.htm

StringReader sr = new StringReader("hello");
StringWriter sw = new StringWriter();
sr.transferTo(sw);
System.out.println(sw.toString());
Canine answered 12/2, 2021 at 17:30 Comment(1)
This is the right answer for Java 10+. Note that Reader gained this method in Java 10 and InputStream gained this method in Java 9. Under the hood, this takes advantage of a character buffer of size 8192 bytes in both cases and uses StringBuffer.append in the StringWriter. This version will not have issues with removing line endings.Rentroll
R
1

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);   
Retsina answered 19/7, 2013 at 16:31 Comment(1)
A bulk read with an array will be faster than reading a single character at a time.Kyanite
C
1

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.

Cowling answered 19/7, 2013 at 16:33 Comment(0)
O
1

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);
}
Outspan answered 21/6, 2018 at 13:29 Comment(0)
T
0

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.

Torrefy answered 19/7, 2013 at 16:29 Comment(0)
V
0

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();
    }
Vicariate answered 19/7, 2013 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.