NIO 规范读写工具——管道 Pipe

x33g5p2x  于2022-05-23 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(252)

一 点睛

两个线程之间单向传递数据时,可以使用 Pipe 规范数据的读写操作。

Pipe 中可以存放数据,并且 Pipe 包含了 SinkChannel 和 SourceChannel 两个 Channel。其中,SinkChannel 用于向 Pipe 中写数据,SourceChannel 用于从 Pipe 中读数据。

二 代码

  1. public static void testPipe() throws IOException {
  2. //创建管道
  3. Pipe pipe = Pipe.open();
  4. ByteBuffer buf = ByteBuffer.allocate(1024);
  5. // 通过 SinkChannel,向 Pipe 中写数据
  6. Pipe.SinkChannel sinkChannel = pipe.sink();
  7. buf.put("helloworld".getBytes());
  8. buf.flip();
  9. sinkChannel.write(buf);
  10. // 通过 SourceChannel,从 Pipe 中读取数据
  11. Pipe.SourceChannel sourceChannel = pipe.source();
  12. buf.flip();
  13. int len = sourceChannel.read(buf);
  14. System.out.println(new String(buf.array(), 0, len));
  15. sourceChannel.close();
  16. sinkChannel.close();
  17. }

三 测试

helloworld

相关文章