管道(Pipe)
Java NIO管道是2个线程之间的单向数据连接。
Pipe有一个source通道和一个 sink通道。数据会被写到sink通道,从source通道读取。
向管道写数据
@Test
public void test() thorws 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());
buf.flip();
while(buf.hasRemaining()){
sinkChannel.write(buf);
}
}
从管道读数据
从读取管道的数据,需要访问source通道。
//从管道读取数据
Pipe.SourceChannel sourceChannel = pipe.source();
调用source通道的read()方法来读取数据
//调用SourceChannel的read()方法读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
sourceChannel.read(buf);