管道流_PipedInputStream与PipedOutputStream

输入和输出可以直接进行连接,通过结合线程使用(一个线程用于写,另一个用于读,因为管道输入流(读)是要读取管道输出流的数据的,又因为输入流中的read方法是阻塞式的,当两个流在同一个线程中时,输入流的read方法没有数据可以读,就发生阻塞,那么这个线程就挂了)

 1 import java.io.IOException;
 2 import java.io.PipedInputStream;
 3 import java.io.PipedOutputStream;
 4 
 5 public class Test {
 6     public static void main(String[] args) throws IOException {
 7         PipedInputStream input = new PipedInputStream();
 8         PipedOutputStream output = new PipedOutputStream();
 9         
10         input.connect(output);
11         
12         new Thread(new Input(input)).start();
13         new Thread(new Output(output)).start();
14     }
15     
16 }
17 class Input implements Runnable{
18     
19     private PipedInputStream in;
20     Input(PipedInputStream in){
21         this.in = in;
22     }
23     public void run(){
24         
25         try {
26             byte[] buf = new byte[1024];
27             int len = in.read(buf);
28             
29             String s = new String(buf,0,len);
30             
31             System.out.println("s="+s);
32             in.close();
33         } catch (Exception e) {
34             
35         }
36         
37     }
38 }
39 
40 class Output implements Runnable{
41     private PipedOutputStream out;
42     Output(PipedOutputStream out){
43         this.out = out;
44     }
45     public void run(){
46         
47         try {
48             Thread.sleep(5000);
49             out.write("hi,管道来了!".getBytes());
50         } catch (Exception e) {
51             
52         }
53     }
54 }
原文地址:https://www.cnblogs.com/LO-ME/p/3599610.html