Java NIO Pipe是兩個線程之間的單向數(shù)據(jù)連接。 一個管道有一個源通道和一個接收通道敛腌。 您將數(shù)據(jù)寫入接收器通道。 然后可以從源通道讀取這些數(shù)據(jù)。
這是一個管道原理的例子:image.png
Creating a Pipe管道
通過調(diào)用Pipe.open()方法打開Pipe奕枢。 這是如何看起來如此:
Pipe pipe = Pipe.open();
Writing to a Pipe
要寫入管道,您需要訪問接收器通道佩微。 這是如何做到的:
Pipe.SinkChannel sinkChannel = pipe.sink();
你可以通過調(diào)用write()方法來寫入SinkChannel缝彬,如下所示:
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);
}
Reading from a Pipe
要從管道中讀取,您需要訪問源通道哺眯。 這是如何做到的:
Pipe.SourceChannel sourceChannel = pipe.source();
要從源通道讀取谷浅,請調(diào)用其read()方法,如下所示:
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
read()方法返回的int告訴有多少字節(jié)讀取到緩沖區(qū)奶卓。