Java NIO管道用於在兩個線程之間建立單向數據連接。它有一個槽通道和源通道。數據正在寫入槽通道,然後可以從源通道讀取該數據。
在Java NIO中,包java.nio.channel.pipe用於按順序讀取和寫入數據。管道用於確保數據必須以寫入管道的相同順序讀取。
下麵來看看管道工作原理的示意圖說明:

創建管道
要創建一個管道,可通過調用Pipe.open()方法打開管道。
打開或創建管道的語法是:
Pipe pp = Pipe.open();
從管道讀取數據
要從管道讀取數據,需要先訪問源通道。 因此,用於訪問源通道的語法是:
Pipe.SourceChannel sc= pipe.source();
要從SourceChannel讀取數據,可調用read()方法,如下所示:
ByteBuffer bb= ByteBuffer.allocate(512);
int bytesRead = inChannel.read(bb);
read()方法返回的整數值用於確定讀入緩衝區的位元組數。
寫入管道
要將數據寫入管道,需要訪問接收器通道。訪問宿通道的語法是:
Pipe.SinkChannel sc= pipe.sink();
要將數據寫入SinkChannel,可調用write()方法,如下所示:
String newData = "The new String is writing in a Pipe..." + System.currentTimeMillis();
ByteBuffer bb= ByteBuffer.allocate(512);
bb.clear();
bb.put(newData.getBytes());
bb.flip();
while(bb.hasRemaining()) {
    SinkChannel.write(bb);
}
基本管道示例:
package com.zaixian;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
public class PipeExample {
    public static void main(String[] args) throws IOException {
        // The Pipe is created
        Pipe pipe = Pipe.open();
        // For accessing the pipe sink channel
        Pipe.SinkChannel skChannel = pipe.sink();
        String td = "Data is successfully sent for checking the java NIO Channel Pipe.";
        ByteBuffer bb = ByteBuffer.allocate(512);
        bb.clear();
        bb.put(td.getBytes());
        bb.flip();
        // write the data into a sink channel.
        while (bb.hasRemaining()) {
            skChannel.write(bb);
        }
        // For accessing the pipe source channel
        Pipe.SourceChannel sourceChannel = pipe.source();
        bb = ByteBuffer.allocate(512);
        // The data is write to the console
        while (sourceChannel.read(bb) > 0) {
            bb.flip();
            while (bb.hasRemaining()) {
                char TestData = (char) bb.get();
                System.out.print(TestData);
            }
            bb.clear();
        }
    }
}
執行上面示例代碼,得到以下結果 -
Data is successfully sent for checking the java NIO Channel Pipe.
						上一篇:
								Java NIO ServerSocketChannel
												下一篇:
								Java NIO字元集
					
					