Java学习之IO流(管道流--PipedStream)

 

管道流
PipedInputStream
PipedOutputStream

注意:输入流和输出流必须在不同的线程中

 1 public class PipedStreamDemo {
 2 
 3     /**
 4      * @param args
 5      * @throws IOException
 6      */
 7     public static void main(String[] args) throws IOException {
 8     PipedInputStream input = new PipedInputStream();
 9     PipedOutputStream output = new PipedOutputStream();
10 
11     input.connect(output);
12     new Thread(new Input(input)).start();
13     new Thread(new Out(output)).start();
14 
15     }
16 }
17 
18 class Input implements Runnable {
19 
20     private PipedInputStream in;
21 
22     public Input(PipedInputStream in) {
23         this.in = in;
24     }
25 
26     @Override
27     public void run() {
28         byte[] buf = new byte[1024];
29         int len;
30         try {
31         len = in.read(buf);
32         String str = new String(buf, 0, len);
33         System.out.println(str);
34         this.in.close();
35         } catch (IOException e) {
36 
37         }
38 
39     }
40 
41 }
42 
43 class Out implements Runnable {
44 
45     private PipedOutputStream out;
46 
47     Out(PipedOutputStream out) {
48         this.out = out;
49     }
50 
51     @Override
52     public void run() {
53         try {
54         out.write("管道流".getBytes());
55         out.close();
56         } catch (IOException e) {
57 
58         }
59     }
60 
61 }

 

posted @ 2020-01-03 10:55  一杯水M  阅读(462)  评论(0编辑  收藏  举报