管道输入/输出流和普通的文件输入/输出流或网络输入/输出流不同之处在于, 它主要用于线程之间的数据传输,而传输的媒介为内存。
管道输入/输出流主要包括了有如下两类实现:
面向字节的管道流:
- PipedOutputStream
- PipedInputStream
面向字符的管道流:
- PipedReader
- PipedWriter
对于Piped类型的流,必须先要进行绑定,也就是调用**connect()**方法,如果没有将输入/输出流绑定起来,对于该流的访问将会抛出异常。
public class Piped {
public static void main(String[] args) {
PipedWriter out = new PipedWriter();
PipedReader in = new PipedReader();
// 将输出流和输入流进行连接,否则在使用时会抛出异常
out.connect(in);
Thread t = new Thread(new Print(in), "PrintThread");
t.start();
int receive = 0;
try {
while((receive = System.in.read()) != -1) {
out.write(receive);
}
} finally {
out.close();
}
}
static class Print implements Runnable {
private PipedReader in;
public Print(PipedReader in) {
this.in = in;
}
public void run() {
int receive = 0;
try {
while((receive = in.read()) != -1) {
System.out.println((char) receive);
}
} catch (IOException ex){
}
}
}
}