日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA的IO编程:管道流

發(fā)布時間:2024/4/17 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA的IO编程:管道流 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

掌握線程通訊流(管道流)的使用

管道流的主要作用是可以進行兩個線程間的通訊,分為管道輸入流(PipeOutputStream)和管道輸出流(PipeInputStream)。

如果要想進行管道輸出,則必須把輸出流連在輸入流之上,在PipeOutputStream上有如下方法用于連接管道。

void connect(PipedInputStream snk) 將此管道輸出流連接到接收者。

要想連接輸入和輸出,必須使用此方法、

?

?

PipeOutputStream輸出方法:

void write(byte[] b, int off, int len) 將 len 字節(jié)從初始偏移量為 off 的指定 byte 數(shù)組寫入該管道輸出流。

PipeInputStream輸入方法:讀取文件的方法

將連接的PipeOutputStream對象實例的輸入流的數(shù)據(jù),通過read方法,把內(nèi)容讀取到數(shù)組中

int read(byte[] b, int off, int len) 將最多 len 個數(shù)據(jù)字節(jié)從此管道輸入流讀入 byte 數(shù)組

?

實例代碼:

package 類集; import java.io.* ; class Send implements Runnable{ // 線程類private PipedOutputStream pos = null ; // 管道輸出流public Send(){this.pos = new PipedOutputStream() ; // 實例化輸出流 }public void run(){String str = "Hello World!!!" ; // 要輸出的內(nèi)容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] ; // 接收內(nèi)容int len = 0 ;try{len = this.pis.read(b) ; // 讀取內(nèi)容}catch(IOException e){e.printStackTrace() ;}try{this.pis.close() ; // 關(guān)閉}catch(IOException e){e.printStackTrace() ;}System.out.println("接收的內(nèi)容為:" + new String(b,0,len)) ;//注意,這里是把讀入的數(shù)組的數(shù)據(jù)輸出,而不是PipeInputStream實例對象輸出,}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() ; // 啟動線程 } };

?

PipeInputStream讀取文件后,讀取的數(shù)據(jù)都存在了PipeInputStream對象的實例中,且類型為byte。

總結(jié):

開發(fā)中很少直接開發(fā)多線程程序,本道程序,只是讓讀者加深讀寫的操作過程,了解,線程間如何通訊。

?

轉(zhuǎn)載于:https://www.cnblogs.com/alsf/p/6785592.html

總結(jié)

以上是生活随笔為你收集整理的JAVA的IO编程:管道流的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。