NIO边看边记 之 管道Pipe(十一)

来源:互联网 发布:mac桌面不显示u盘图标 编辑:程序博客网 时间:2024/05/14 16:18

NIO支持管道操作。管道模型如下所示:
这里写图片描述
管道通常用来两个线程来传输数据。
其中SinkChannel用于往Pipe中写数据,SourceChannel用于从Pipe中读数据
1.创建管道

Pipe pipe = Pipe.open();

2.写管道

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);}

3.读管道

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

read的返回值表示读到的字节数。

0 0