O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Piped Readers and Writers

Piped readers and writers do for character streams what piped input and output streams do for byte streams: they allow two threads to communicate. Character output from one thread becomes character input for the other thread:

public class PipedWriter extends Writer
public class PipedReader extends Reader

The PipedWriter class has two constructors. The first constructs an unconnected PipedWriter object. The second constructs one that’s connected to the PipedReader object sink:

public PipedWriter()
public PipedWriter(PipedReader sink) throws IOException

The PipedReader class also has two constructors. Again, the first constructor creates an unconnected PipedReader object. The second constructs one that’s connected to the PipedWriter object source:

public PipedReader()
public PipedReader(PipedWriter source) throws IOException

Piped readers and writers are normally created in pairs. The piped writer becomes the underlying source for the piped reader. This is one of the few cases where a reader does not have an underlying input stream. For example:

PipedWriter pw = new PipedWriter();
PipedReader pr = new PipedReader(pw);

This simple example is a little deceptive, because these lines of code will normally be in different methods and perhaps even different classes. Some mechanism must be established to pass a reference to the PipedWriter into the thread that handles the PipedReader, or you can create them in the same thread, then pass a reference to the connected stream ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required