Java NIO管道(Pipe)是两个进程间的单向连接。管道有一个源通道和一个sink通道,往sink通道中写数据,数据就能从source通道中读取。
Pipe Internals
调用Pipe.open()方法就能打开一个Pipe:
Pipe pipe = Pipe.open()
往Pipe中写,需要访问sink通道,例如:
Pipe.SinkChannel sinkChannel = pipe.sink();
调用SinkChannel的write()方法就能往里面写数据了,例如:
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);
}
读Pipe需要访问source通道,就像这样:
Pipe.SourceChannel sourceChannel = pipe.source();
调用source通道的read()方法可以读取里面的数据,例如:
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
read()方法返回的int表示读了多少字节的数据到缓冲区中。