Java IO: PipedReader

Jakob Jenkov
Last update: 2015-09-07

The Java PipedReader class (java.io.PipedReader) makes it possible to read the contents of a pipe as a stream of characters. As such it works very much like a PipedInputStream except the PipedInputStream is byte based, not character based. The PipedReader is intended to read text, in other words.

A Java PipedReader must be connected to a PipedWriter. Often, the PipedReader and PipedWriter are used by different threads. Only one PipedReader can be connected to the same PipedWriter.

PipedReader Example

Here is a simple Java PipedReader example:

PipedWriter pipedWriter = new PipedWriter();
PipedReader pipedReader = new PipedReader(pipedWriter);

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

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

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

read()

The read() method of a Java PipedReader returns an int which contains the char value of the character read. If the read() method returns -1, there is no more data to read in the PipedReader, and it can be closed. That is, -1 as int value, not -1 as byte value. There is a difference here!

Java IO Pipes

As you can see in the example above, a PipedReader needs to be connected to a PipedWriter. When these two character streams are connected they form a pipe. To learn more about Java IO pipes, go to Java IO: Pipes.

Closing a PipedReader

When you are finished reading characters from a Java PipedReader you should remember to close it. Closing a PipedReader is done by calling its close() method.

Closing a PipedReader does not close the PipedWriter it is connected to. But - even if the PipedReader is closed you cannot connect a new PipedReader to the PipedWriter.

Here is how closing a Java PipedReader looks:

pipedReader.close();

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a PipedReader looks with the try-with-resources construct:

try(PipedReader pipedReader =
    new PipedReader(pipedWriter)){

    int data = pipedReader.read();
    while(data != -) {
        System.out.print((char) data));
        data = pipedReader.read();
    }
}

Notice how there is no longer any explicit close() method call to the PipedReader instance. The try-with-resources construct takes care of that.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















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
Previous
Next tutorial in this tutorial trail
Next