PipedInput OutputStream example

PipedInputStream and PipedOutputStream are classes provided in java.io package. PipedInputStream is inherited from InputStream, and PipedOutputStream is inherited from OutputStream.
A piped input stream should be connected to a piped output stream, using connect() method(as shown in below example). Data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.

Below is an example, in which main thread reads characters from PipedInputStream, and other thread writes characters to PipeOutputStream.


import java.io.*;

class MyThread extends Thread{
    static String str = "Hello How are you";
    //creating one thread t1 which writes the data
        public void run(){
            for(int i=0;i<=str.length();i++){
            try{
                PipedInputOutput1.pout.write(str.charAt(i));
                Thread.sleep(1000);  //1000 milliseconds
            }catch(Exception e){
            System.out.println(e.getMessage());
            }
            } //end of for
        }  //end of run()

}

class PipedInputOutput1{
    final static PipedOutputStream pout=new PipedOutputStream();
    final static PipedInputStream pin=new PipedInputStream();

    public static void main(String args[])throws Exception{
        pout.connect(pin);//connecting the streams

        MyThread t1 = new MyThread();
        //creating another thread t2 which reads the data

        //starting both threads
        t1.start();

        try{
            for(int i=0;i<=MyThread.str.length();i++)
            {
                System.out.println((char)pin.read());
            }
        }catch(Exception e){
        System.out.println(e.getMessage());
        }
    }
}


You may also like to read:
SequenceInputStream purpose
Convert String to a Stream
How to take input from key board
Java Serialization example