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 =;
while(data != -1) {
  //do something with data...

  data =;

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:


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 =;
    while(data != -1) {
        //do something with data
        data =;

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

Java ForkJoinPool

P2P Networks Introduction


Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Next tutorial in this tutorial trail