Using PipedInputStream and PipedOutputStream

A PipedInputStream and PipedOutputStream are used to communicate between threads. If you connect the two together, whatever you write to the PipedOutputStream, you receive on the PipedInputStream.

Here’s an example:

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      try {
         PipedOutputStream pos = new PipedOutputStream();
         PipedInputStream pis = new PipedInputStream(pos);
 
         BufferedInputStream bis = new BufferedInputStream(pis);
  
         new DataCollector(pos).start();
  
         // thread has started to produce data, start 
         // reading data through the pipe here
         while (true) {
            byte[] buffer = new byte[64];
            bis.read(buffer);
            System.out.println("Received: " + new String(buffer));
         }
      }
      catch(IOException e) { 
         e.printStackTrace();
      }
   }
}
 
class DataCollector extends Thread
{
   private BufferedOutputStream bos;
 
   public DataCollector(OutputStream out) {
      this.bos = new BufferedOutputStream(out);
   }
  
   public void run() {
      // generate data here
      int count=0;
      while (true) {
         try {
            count++;
            String data = "data [" + count + "]";
            bos.write(data.getBytes());
            // perform a flush here to make the receiver get it right away
            bos.flush();
            sleep(1000);
         }
         catch(Exception e) {
            e.printStackTrace();
         }
      }
   }
}

outputs:

Received: data [1]
Received: data [2]
Received: data [3]
Received: data [4]
Received: data [5]
Received: data [6]
Received: data [7]
Received: data [8]
Received: data [9]
. . .