十三、Java NIO 管道

所有文章

https://www.cnblogs.com/lay2017/p/12901123.html

正文

NIO的管道(Pipe)是一种打通两个线程之间数据传输的一种方式。Pipe包含两个channel:

1)Source Channel

2)Sink Channel

你可以向SinkChannel写入数据,然后从SourceChannel读取出来。如图

 创建一个Pipe

Pipe pipe = Pipe.open();

写入数据到Pipe

Pipe.SinkChannel sinkChannel = pipe.sink();
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读取数据

Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);
原文地址:https://www.cnblogs.com/lay2017/p/12915247.html