Home  >  Core Java

Java PipedWriter and PipedReader Example

By Arvind Rai, July 19, 2014
java.io.PipedWriter and java.io.PipedReader has been introduced in JDK 1.1. PipedWriter and PipedReader both are connected to each other to create a communication pipe. PipedWriter and PipedReader both works on character output and input stream. Sending end is PipedWriter and receiving end is PipedReader. If pipe broken, IOException is thrown. Find the example.
PipedReaderWriterDemo.java
package com.cp.io;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PipedReaderWriterDemo {
   final static PipedWriter pipedWriter = new PipedWriter();
   final static PipedReader pipedReader = new PipedReader();
   final char c[] = {'H','e','l','l','o',' ','W','o','r','l','d','!'};
   class PipedWriterThread implements Runnable{
		@Override
		public void run() {
			    try{
					pipedWriter.write(c);
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
   }
   
  class PipedReaderThread implements Runnable{
		@Override
		public void run() {
				try {
					int i=0;
					while((i=pipedReader.read())!=-1){
						System.out.print((char)i);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
   
    public static void main(String[] args) {
    	try {
    		pipedWriter.connect(pipedReader);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	ExecutorService service = Executors.newFixedThreadPool(2);
    	service.execute(new PipedReaderWriterDemo().new PipedWriterThread());
    	service.execute(new PipedReaderWriterDemo().new PipedReaderThread());
	}
} 
Output is Hello World!
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us