Java NIO 管道是2個線程之間的單向數據鏈接。Pipe有一個source通道和一個sink通道。數據會被寫到sink通道,從source通道讀取。spa
這裏是Pipe原理的圖示:線程
建立管道
經過Pipe.open()方法打開管道。例如:code
Pipe pipe = Pipe.open();
向管道寫數據
要向管道寫數據,須要訪問sink通道。像這樣:ip
Pipe.SinkChannel sinkChannel = pipe.sink();
經過調用SinkChannel的write()方法,將數據寫入SinkChannel,像這樣:get
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); }
從管道讀取數據
從讀取管道的數據,須要訪問source通道,像這樣:it
Pipe.SourceChannel sourceChannel = pipe.source();
調用source通道的read()方法來讀取數據,像這樣:pip
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = sourceChannel.read(buf);
read()方法返回的int值會告訴咱們多少字節被讀進了緩衝區。class