[ Back | Previous | Next ]

Using PipedOutputStream and PipedInputStream.

Package:
java.io.*
Product:
JDK
Release:
1.1.x
Related Links:
General
File
FilenameFilter
FileWriter
JPEGCodec
ObjectInputStream
OutputStream
PipedInputStream
PrintWriter
StreamTokenizer
Comment:
How can we use the pipedout- and pipedinputstream. The basic use lies in combination with thread. For example we have a reader thread, a decode thread 
and a writer thread. The first one reads the information and sends it to an outputstream, this is picked up by the 
decode thread to decode the stream and send it to it output, and finally this is being picked up by the writer thread to write it to its output.

Graphically this is what is happening:

      FileInputStream readIn = new FileInputStream(inputFile);

      // The first pipe
      PipedInputStream  decodeIn = new PipedInputStream();
      PipedOutputStream readOut = new PipedOutputStream(decodeIn);

      // The second pipe
      PipedInputStream  writeIn = new PipedInputStream();
      PipedOutputStream decodeOut = new PipedOutputStream(writeIn);

      FileOutputStream output = new FileOutputStream(outputFile);

      pipeThread reader = new pipeThread("reader", readIn, readOut);
      decodeThread decode = new decodeThread("decode",decodeIn , decodeOut , bits);
      pipeThread writer = new pipeThread ("writer", writeIn, writeOut);

      reader.start();
      decode.start(); 
      writer.start();
Example
The following example gives a working example:
import java.io.*;

/** Test class for reading keyboard input from commandline
 */
class ReadThread extends Thread implements Runnable {

  InputStream pi = null;
  OutputStream po = null;    
  String process = null;

  ReadThread( String process, InputStream pi, OutputStream po) {
    this.pi = pi;    this.po = po;    this.process = process;  }

  public void run() {
    int ch;    byte[] buffer = new byte[512];    int bytes_read;
    try { 
        for(;;) {
            bytes_read = pi.read(buffer);
            if (bytes_read == -1) { return; }
            po.write(buffer, 0, bytes_read);
        }
    } catch (Exception e) {  e.printStackTrace(); 
    } finally {  }
  }

}

class SystemStream {

 public static void main( String [] args) {
    try {
      int ch;
      while (true) {
        PipedInputStream  writeIn = new PipedInputStream();
        PipedOutputStream readOut = new PipedOutputStream( writeIn );

        FileOutputStream writeOut = new FileOutputStream("out");

        ReadThread rt = new ReadThread("reader", System.in, readOut );
        ReadThread wt = new ReadThread("writer",  writeIn, System.out );

        rt.start();
        wt.start();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
1