java PipedOutputStream、PipedInputStream的使用


1、管道流的使用

 1 package cn.kongxh.io6;
 2 import java.io.* ;
 3 class Send implements Runnable{            // 線程類
 4     private PipedOutputStream pos = null ;    // 管道輸出流
 5     public Send(){
 6         this.pos = new PipedOutputStream() ;    // 實例化輸出流
 7     }
 8     public void run(){
 9         String str = "Hello World!!!" ;    // 要輸出的內容
10         try{
11             this.pos.write(str.getBytes()) ;
12         }catch(IOException e){
13             e.printStackTrace() ;
14         }
15         try{
16             this.pos.close() ;
17         }catch(IOException e){
18             e.printStackTrace() ;
19         }
20     }
21     public PipedOutputStream getPos(){    // 得到此線程的管道輸出流
22         return this.pos ;    
23     }
24 };
25 class Receive implements Runnable{
26     private PipedInputStream pis = null ;    // 管道輸入流
27     public Receive(){
28         this.pis = new PipedInputStream() ;    // 實例化輸入流
29     }
30     public void run(){
31         byte b[] = new byte[1024] ;    // 接收內容
32         int len = 0 ;
33         try{
34             len = this.pis.read(b) ;    // 讀取內容
35         }catch(IOException e){
36             e.printStackTrace() ;
37         }
38         try{
39             this.pis.close() ;    // 關閉
40         }catch(IOException e){
41             e.printStackTrace() ;
42         }
43         System.out.println("接收的內容為:" + new String(b,0,len)) ;
44     }
45     public PipedInputStream getPis(){
46         return this.pis ;
47     }
48 };
49 public class PipedDemo{
50     public static void main(String args[]){
51         Send s = new Send() ;
52         Receive r = new Receive() ;
53         try{
54             s.getPos().connect(r.getPis()) ;    // 連接管道
55         }catch(IOException e){
56             e.printStackTrace() ;
57         }
58         new Thread(s).start() ;    // 啟動線程
59         new Thread(r).start() ;    // 啟動線程
60     }
61 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM