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

5.1 向管道写数据
public void test01() throws IOException {
String str = "测试数据";
//创建管道
Pipe pipe = Pipe.open();
//向管道写输入
Pipe.SinkChannel sinkChannel = pipe.sink();
//通过 SinkChannel 的write() 方法写数据
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
buf.put(str.getBytes());
while (buf.hasRemaining()) {
sinkChannel.write(buf);
}
}
5.2 向管道读数据
public void test02() throws IOException {
//创建管道
Pipe pipe = Pipe.open();
//从管道读取数据
Pipe.SourceChannel sourceChannel = pipe.source();
//调用 SourceChannel 的 read() 方法取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
sourceChannel.read(buf);
}
网友评论