閱讀658 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java IO--管道流PipedOutputStream/PipedInputStream

管道流


import java.io.* ;
class Send implements Runnable{			// 線程類
	private PipedOutputStream pos = null ;	// 管道輸出流
	public Send(){
		this.pos = new PipedOutputStream() ;	// 實例化輸出流
	}
	public void run(){
		String str = "Hello World!!!" ;	// 要輸出的內容
		try{
			this.pos.write(str.getBytes()) ;
		}catch(IOException e){
			e.printStackTrace() ;
		}
		try{
			this.pos.close() ;
		}catch(IOException e){
			e.printStackTrace() ;
		}
	}
	public PipedOutputStream getPos(){	// 得到此線程的管道輸出流
		return this.pos ;	
	}
};
class Receive implements Runnable{
	private PipedInputStream pis = null ;	// 管道輸入流
	public Receive(){
		this.pis = new PipedInputStream() ;	// 實例化輸入流
	}
	public void run(){
		byte b[] = new byte[1024] ;	// 接收內容
		int len = 0 ;
		try{
			len = this.pis.read(b) ;	// 讀取內容
		}catch(IOException e){
			e.printStackTrace() ;
		}
		try{
			this.pis.close() ;	// 關閉
		}catch(IOException e){
			e.printStackTrace() ;
		}
		System.out.println("接收的內容為:" + new String(b,0,len)) ;
	}
	public PipedInputStream getPis(){
		return this.pis ;
	}
};
public class PipedDemo{
	public static void main(String args[]){
		Send s = new Send() ;
		Receive r = new Receive() ;
		try{
			s.getPos().connect(r.getPis()) ;	// 連接管道
		}catch(IOException e){
			e.printStackTrace() ;
		}
		new Thread(s).start() ;	// 啟動線程
		new Thread(r).start() ;	// 啟動線程
	}
};


最後更新:2017-04-03 14:54:02

  上一篇:go Linux驅動編寫的方法學習
  下一篇:go poj 1477 Box of Bricks