PipedReader PipedWriter Example

PipedReader PipedWriter Example


Piping Data PipedReader PipedWriter

Summary: By the end you read this tutorial "Piping Data PipedReader PipedWriter", you will understand passing data between two running processes or threads.

The PipedReader and PipedWriter are character streams. Similar in byte streams are PipedInputStream and PipedOutputStream. These streams use a concept called pipe. Pipe is used to pass data between two running Java processes or threads. A pipe is a data flow conduit (channel).

Following are the class signatures.

public class PipedReader extends Reader
public class PipedWriter extends Writer

Now let us go for PipedReader PipedWriter Example

In the following code, the data is passed between two running processes.

PipedReader PipedWriter Example
Output screen on PipedReader PipedWriter Example

PipedWriter pwriter = new PipedWriter();
PipedReader preader = new PipedReader(pwriter);

The PipedWriter object pwriter is connected to PipedReader object preader using constructor. Any data written to PipedWriter is available implicitly to PipedReader for reading.

In a for loop, the data 0 to 10 numbers is written to PipedWriter object, pwriter. Later the data is read using PipedReader object preader in another for loop. Observe, even though the PipedWriter object is closed before PipedReader reads, the data is not lost.

The above two statements can be modified using default constructors. Later connected together using connect() method as follows.

PipedWriter pwriter = new PipedWriter();
PipedReader preader = new PipedReader();
preader.connect(pwriter);

The connection can be affected in the other way also as follows.

pwriter.connect(preader);

It means, after all, any way they must be connected.

One thought on “PipedReader PipedWriter Example

Leave a Reply

Your email address will not be published. Required fields are marked *