You know the power of pipe (“|”) operator in Unix. It helps you to redirect output from one command to another. PipedReader and PipedWriter classes in java.io package helps you to do the same. It helps you to redirect the read input into writer seamlessly. In unix, two process on different address space can communicate using pipe but in java two threads in the same JVM can communicate using Piped ByteStream/CharacterStream.
Below given sample program demonstrate the use piped character streams. This program read from the console and redirect console input to another thread using piped character stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package com.ourownjava.corejava.stream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PipedReader; import java.io.PipedWriter; /** * @date 1st May, 2011 * @author ourownjava.com * * To demonstrate the use of piped character streams. * Example program for piped character stream in java. * */ public class PipedReaderExample { public static void main(String args[]) throws IOException{ final PipedReader reader = new PipedReader(); final PipedWriter writer = new PipedWriter(reader); final Thread readerThread = new Thread(new ReaderThread(writer)); final Thread writerThread = new Thread(new WriterThread(reader)); readerThread.start(); writerThread.start(); } } class ReaderThread implements Runnable{ PipedWriter writer; public ReaderThread(PipedWriter writer){ this.writer = writer; } public void run() { final InputStreamReader streamReader = new InputStreamReader(System.in); final BufferedReader bufferedReader = new BufferedReader(streamReader); try { while (true) { //sample implementation reading from console //real implementation can be reading from a socket or a file //or from server side code String line = bufferedReader.readLine(); writer.write(line); } } catch (IOException e) { e.printStackTrace(); } } } class WriterThread implements Runnable{ PipedReader reader; public WriterThread(PipedReader reader){ this.reader = reader; } public void run() { while(true){ try { char c; while( (c = (char)reader.read()) != -1){ //write your business logic here //could be writing into a file //could be processing the date System.out.print(c); } } catch (IOException e) { e.printStackTrace(); } } } } |
Pingback: Use of PipedReader and PipedWriter in java. | Clean Java