Java IO: PipedReader

Jakob Jenkov
Last update: 2015-09-07

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

  data =;

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.


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:


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 =;
    while(data != -) {
        System.out.print((char) data));
        data =;

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 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