5. PipedInputStream과 PipedOutputStream
PipedInputStream과 PipedOutputStream을 이해하려면 먼저 파이프가 무엇인지 알아야 한다.
유닉스 시스템에서 자주 사용하는 기호중에 파이프 기호(’|‘)가 있다. 이는 앞 명령어에서 출력된 문자들을 파이프 기호 명령을 통해 뒤의 명령어로 전달할 수 있다. ( ex : ls | wc )
자바에서 제공하는 Piped도 위의 파이프 기호와 같은 기능을 수행한다. PipedOutputStream으로 출력한 결과를 PipedInputStream을 통해서 읽어 들일수 있게 만들 수 있는 것이다.
보통 이러한 예는 멀티스레드에서 종종 사용된다. 하나의 스레드가 읽어 들인 내용을 다른 스레드에게 전달하고자 할때 PipedInputStream과 PipedOutputStream을 이용하는 것이다.
import java.io.*;
class ReadThread extends Thread implements Runnable
{
InputStream pi = null;
OutputStream po = null;
ReadThread ( InputStream pi, OutputStream po)
{
this.pi = pi;
this.po = po;
}
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{
}
}
}
public class SystemStream
{
public static void main(String[] args)
{
try {
int ch;
while(true)
{
PipedInputStream writeIn = new PipedInputStream();
PipedOutputStream readOut = new PipedOutputStream(writeIn);
ReadThread rt = new ReadThread(System.in, readOut);
ReadThread wt = new ReadThread(writeIn, System.out);
rt.start();
wt.start();
}
} catch (Exception e) {
}
}
}
출처 : 김성박 송지훈 공저, 『 자바 IO & NIO 네트워크 프로그래밍』, 한빛미디어(2004.9.30), 4장 인용.