Java IO: StringReader

Jakob Jenkov
Last update: 2015-09-10

The Java StringReader class enables you to turn an ordinary String into a Reader. This is useful if you have data as a String but need to pass that String to a component that only accepts a Reader.

StringReader Example

Here is a simple Java StringReader example:

String input = "Input String... ";
StringReader stringReader = new StringReader(input);

int data = stringReader.read();
while(data != -1) {
  //do something with data...
  doSomethingWithData(data);

  data = stringReader.read();
}
stringReader.close();

This example first creates a StringReader, passing a String as parameter to the StringReader constructor. Second, the example reads the characters one character at a time from the StringReader. Finally the StringReader is closed.

Closing a StringReader

Closing a Java StringReader can be done using the close() method like this:

stringReader.close();

Or you can close the StringReader using the Java 7 try-with-resources construct. Here is how that looks:

try(StringReader stringReader =
    new StringReader(chars, offset, length)){

    int data = stringReader.read();
    while(data != -1) {
        //do something with data
        data = stringReader.read();
    }
}

Notice that there is no explicit close() call on the StringReader. The try block takes care of that.

However, since the StringReader is not using any underlying system resources like files or network sockets, closing the StringReader is not crucial.

Jakob Jenkov

Featured Videos




















Advertisements

High-Performance
Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next