管道流

 1 import java.io.IOException;
 2 import java.io.PipedInputStream;
 3 import java.io.PipedOutputStream;
 4 
 5 public class PipedInputStreamDemo {
 6     public static void main(String[] args) throws IOException{ 
 7         PipedInputStream pis =new PipedInputStream();
 8         PipedOutputStream pos =new PipedOutputStream();
 9         pis.connect(pos);
10         Reader r =new Reader(pis);
11         Writer w =new Writer(pos);
12         new Thread(r).start();
13         new Thread(w).start();
14     }
15 
16 }
17 class Reader implements Runnable{
18     private PipedInputStream pis;
19     
20     public Reader(PipedInputStream pis) {
21         super();
22         this.pis = pis;
23     }
24 
25     public void run(){
26         byte[] buf =new byte[1024];
27         int ch =0;
28         try {
29             while((ch=pis.read(buf))!=-1){
30                 System.out.println(new String(buf,0,ch));
31             }
32         } catch (IOException e) {
33             // TODO Auto-generated catch block
34             e.printStackTrace();
35         }
36     }
37 }
38 class Writer implements Runnable{
39     private PipedOutputStream pos;
40     
41     public Writer(PipedOutputStream pos) {
42         super();
43         this.pos = pos;
44     }
45 
46     public void run(){
47         try {
48             pos.write("abcdefgh".getBytes());
49             pos.close();
50         } catch (IOException e) {
51             // TODO Auto-generated catch block
52             e.printStackTrace();
53         }
54     }
55 }

 

posted @ 2012-06-22 13:28  Carve_Time  阅读(179)  评论(0编辑  收藏  举报