java的nio中的管道,就類似于實際中的管道,有兩端,一段作為輸入,一段作為輸出。也就是說,在創建了一個管道后,既可以對管道進行寫,也可以對管道進行讀,不過這兩種操作要分別在兩端進行。有點類似于隊列的方式。
這里是pipe原理的圖示:
創建管道
通過pipe.open()方法打開管道。例如:
pipe pipe = pipe.open();
向管道寫數據
要向管道寫數據,需要訪問sink通道。像這樣:
pipe.sinkchannel sinkchannel = pipe.sink();
通過調用sinkchannel的write()方法,將數據寫入sinkchannel,像這樣:
1
2
3
4
5
6
7
8
|
string newdata = "new string to write to file..." + system.currenttimemillis(); bytebuffer buf = bytebuffer.allocate( 48 ); buf.clear(); buf.put(newdata.getbytes()); buf.flip(); while (buf.hasremaining()) { sinkchannel.write(buf); } |
我們在測試例子中給出一個非常簡單的管道操作,先向管道寫入內容,再從管道讀出內容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package com.test.nio; import java.io.ioexception; import java.nio.bytebuffer; import java.nio.channels.pipe; public class testpipea { /** * @param args * @throws exception */ public static void main(string[] args) throws exception { //創建一個管道 pipe pipe=pipe.open(); //創建一個寫管道 pipe.sinkchannel sinkchannel=pipe.sink(); string newdata= "itbuluoge.com says:" +system.currenttimemillis(); bytebuffer buf=bytebuffer.allocate( 48 ); buf.clear(); buf.put(newdata.getbytes()); buf.flip(); /*向管道寫入內容*/ while(buf.hasremaining()) { sinkchannel.write(buf); } /*創建一個讀管道*/ pipe.sourcechannel sourcechannel=pipe.source(); bytebuffer getbuf=bytebuffer.allocate(48); int bytesread=sourcechannel.read(getbuf); getbuf.flip(); /*從管道讀出內容*/ while (getbuf.hasremaining()) { system.out.print(( char )getbuf.get()); } } } |
輸出結果
我們可以看到,已經可以完成我們需要的目標了。注意,我在這個地方編程的時候,出現了一點錯誤,就是我在讀取管道的時候,沒有設置getbuf.flip(),導致無法讀出數據,這個函數非常重要,在完成buffer讀取內容之后,一定要設置一下讀標志,恢復指針到原始位置,才能讀取到全部內容。
以上就是本文關于java的nio管道用法代碼分享的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/itbuluoge/article/details/39552769