概述
Java NIO 管道是2个线程之间的单向数据连接。Pipe
有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
创建管道
通过Pipe.open()
方法打开管道
Pipe pipe = Pipe.open();
要向管道写数据,需要访问sink通道。
//创建写管道
Pipe.SinkChannel sinkChannel = pipe.sink();
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
//position将被设回0,limit被设置成 capacity的值,重置buffer
buf.clear();
buf.put(newData.getBytes());
//将Buffer从写模式切换到读模式
buf.flip();
while(buf.hasRemaining()) {
sinkChannel.write(buf);
}