PipedReader PipedWriter Example

April 22, 2011 | I/O streams in java

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.

import java.io.*;
public class PRWDemo
  public static void main(String args[]) throws IOException
    PipedWriter pwriter = new PipedWriter();
    PipedReader preader = new PipedReader(pwriter);
                                            // data writing to PrintWriter 
    for(int i=0; i< 10; i++)
                                           // data reading using PipedReader
    int temp;
    while((temp=preader.read()) != -1)

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.


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