Java-NIO(九):管道 (Pipe)

时间:2023-03-09 04:49:42
Java-NIO(九):管道 (Pipe)

Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

Java-NIO(九):管道 (Pipe)

代码使用示例:

 @Test
public void testPipe() throws IOException {
// 1、获取通道
Pipe pipe = Pipe.open(); // 2、获取sink管道,用来传送数据
Pipe.SinkChannel sinkChannel = pipe.sink(); // 3、申请一定大小的缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put("123232142345234".getBytes());
byteBuffer.flip(); // 4、sink发送数据
sinkChannel.write(byteBuffer); // 5、创建接收pipe数据的source管道
Pipe.SourceChannel sourceChannel = pipe.source();
// 6、接收数据,并保存到缓冲区中
ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);
byteBuffer2.flip();
int length = sourceChannel.read(byteBuffer2); System.out.println(new String(byteBuffer2.array(), 0, length)); sourceChannel.close();
sinkChannel.close(); }