管道读取流和管道写入流可以像管道一样对接上,管道读取流就可以读取管道写入流写入的数据。需要注意的是需要加入多线程技术,因为单线程,先执行read,会发生死锁,因为read方法是阻塞式的,没有数据的read方法会让线程一直等待。
具体代码及测试
1 package FileDemo;
2
3 import java.io.IOException;
4 import java.io.PipedInputStream;
5 import java.io.PipedOutputStream;
6
7 public class PipedStreamDemo {
8
9 /**
10 * @param args
11 * @throws IOException
12 */
13 public static void main(String[] args) throws IOException {
14
15 PipedInputStream pipin = new PipedInputStream();
16 PipedOutputStream pipout = new PipedOutputStream();
17 pipin.connect(pipout);
18 new Thread(new Input(pipin)).start();
19 new Thread(new Output(pipout)).start();
20 }
21
22 }
23
24 class Output implements Runnable {// 管道写入流
25 private PipedOutputStream out;
26
27 Output(PipedOutputStream out) {
28 this.out = out;
29 }
30
31 @Override
32 public void run() {
33 try {
34 // Thread.sleep(50);
35 out.write("管道流PipedStream".getBytes());// 字节输出流不可以直接写入字符串
36 } catch (Exception e) {
37 // TODO: handle exception
38 }
39 }
40 }
41
42 class Input implements Runnable {// 管道读取流
43 private PipedInputStream in;
44
45 Input(PipedInputStream in) {
46 this.in = in;
47 }
48
49 @Override
50 public void run() {
51 try {
52 byte[] buf = new byte[1024];
53 int len = 0;
54 len = in.read(buf);
55 System.out.println(new String(buf, 0, len));
56 in.close();
57 } catch (Exception e) {
58 // TODO: handle exception
59 }
60 }
61
62 }