What are java.io.PipedReader and java.io.PipedWriter used for?

Piped streams are a mechanism in Java for setting up a stream of data between 2 threads. Piped streams come in pairs of streams – an input one and an output one. Data written to the output stream should show up in the input stream at the other end of the pipe. You can think of piped streams as a buffer with a connection at each end.
Let’s look at a simple example of working with piped streams. The example consists of two classes: MyThread (the second thread required for the pipe) and PipeDemo1 (a demonstration of piped streams)
The class MyThread stores in its constructor a reference to an object of the class Writer, which is derived from the class Stream. That is the key thing you need to keep in mind.

JAVA
class PipeWriterThread extends Thread {
    private Writer out;
    public PipeWriterThread(Writer out) {
        this.out = out;
    }
    public void run() {
        //-Write to the start of the pipe.
        try {
            BufferedWriter bufferedWriter = new
            BufferedWriter(out);
            bufferedWriter.write("testing");
            bufferedWriter.newLine();
            bufferedWriter.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

To work with piped streams, we need to create both ends of the pipe – here they are represented by objects of the classes PipedWriter and PipedReader. To connect them, it is enough to store a reference to the other one in the constructor of one of them. Do not store this reference in both; not that it would be technically impossible in theory, but in practice it is. For reading, I create an object BufferedReader, which reads the listener for me – the reader end of the pipe.

JAVA
public class PipeDemo1
{
    public static void main(String args[])
    throws IOException
    {
        //-Create the "pipe"
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader(writer);
        //-Write to the pipe via a thread
        new PipeWriterThread(writer).start();
        //-Read from the end of the pipe.
        BufferedReader bufferedReader = new
        BufferedReader(reader);
        String line = bufferedReader.readLine();
        bufferedReader.close();
        System.out.println(line);
    }
}
Categories

Leave a Reply