Java - PipedReader and PipedWriter example

Posted on November 9, 2016


PipedReader class and PipedWriter class are piped character stream .Pipes are used to send the output from one program (or thread) into the input of another.

Following is an example of using the PipedReader and PipedWriter. In this example one thread writes data to pipe and another thread reads data from that pipe.

PipedReaderWriterExample.java

package com.boraji.tutorial.io;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author imssbora
 */
public class PipedReaderWriterExample {
   public static void main(String[] args) throws Exception {
      final PipedReader pipedReader = new PipedReader();
      final PipedWriter pipedWriter = new PipedWriter();

      // Connect pipe
      pipedReader.connect(pipedWriter);

      // Writing data to pipe
      Thread writerThread = new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               for (int i = 65; i <= 70; i++) {
                  pipedWriter.write((char) i);
                  Thread.sleep(500);
               }
               pipedWriter.close();
            } catch (IOException | InterruptedException e) {
               e.printStackTrace();
            }
         }
      });

      // Reading data from pipe
      Thread readerThread = new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               int i;
               while ((i = pipedReader.read()) != -1) {
                  System.out.println((char) i);
                  Thread.sleep(1000);
               }
               pipedReader.close();
            } catch (IOException | InterruptedException e) {
               e.printStackTrace();
            }
         }
      });

      // Start thread
      writerThread.start();
      readerThread.start();
   }
}

Output

A
B
C
D
E
F