十三、Java NIO 管道
2021-01-18 07:12
标签:com channel col alt pip string log while 读取数据 https://www.cnblogs.com/lay2017/p/12901123.html NIO的管道(Pipe)是一种打通两个线程之间数据传输的一种方式。Pipe包含两个channel: 1)Source Channel 2)Sink Channel 你可以向SinkChannel写入数据,然后从SourceChannel读取出来。如图 十三、Java NIO 管道 标签:com channel col alt pip string log while 读取数据 原文地址:https://www.cnblogs.com/lay2017/p/12915247.html所有文章
正文
创建一个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);