Home  >  Core Java

Java PipedOutputStream and PipedInputStream Example

By Arvind Rai, July 19, 2014
Java.io.PipedOutputStream and java.io.PipedInputStream has been introduced in JDK 1.0. PipedOutputStream and PipedInputStream both are connected to each other to create a communication pipe. PipedOutputStream is the sending end and PipedInputStream is the receiving end of the pipe. Both ends should not be handled by single thread otherwise deadlock may occur. If any thread stops working, pipe is said to be broken.
Java PipedOutputStream and PipedInputStream Example

PipedInputOutputDemo.java
package com.cp.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PipedInputOutputDemo {
   final static PipedOutputStream pipedOut = new PipedOutputStream();
   final static PipedInputStream pipedIn = new PipedInputStream();
   
   class PipedOutputThread implements Runnable{
		@Override
		public void run() {
			for(int i=1;i<=5;i++){
				try {
					pipedOut.write(("Message "+i+"\n").getBytes());
					Thread.sleep(500);
				} catch (IOException e) {
					e.printStackTrace();
				}catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
   }
   
   class PipedInputThread implements Runnable{
		@Override
		public void run() {
				try {
					int i=0;
					while((i=pipedIn.read())!=-1){
						System.out.print((char)i);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
    }
   
    public static void main(String[] args) {
    	        try {
			pipedOut.connect(pipedIn);
		} catch (IOException e) {
			e.printStackTrace();
		}
      	        ExecutorService service = Executors.newFixedThreadPool(2);
     	        service.execute(new PipedInputOutputDemo().new PipedOutputThread());
     	        service.execute(new PipedInputOutputDemo().new PipedInputThread());
   }
} 
Output is given as below.
Message 1
Message 2
Message 3
Message 4
Message 5 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us