天天看点

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

NIO支持管道操作。管道模型如下所示:

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

管道通常用来两个线程来传输数据。

其中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();
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
    sinkChannel.write(buf);
}
           

3.读管道

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

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