Java NIO Pipe是两个线程之间的单向数据连接,Pipe具有source channel和sink channel。写数据到sink channel,然后可以从source channel读取此数据。
这是Pipe原理的说明:
1.创建Pipe
可以通过调用Pipe.open()方法来打开Pipe:
Pipe pipe = Pipe.open();
2.写数据到Pipe
要写入Pipe,需要访问sink channel:
Pipe.SinkChannel sinkChannel = pipe.sink();
可以通过调用SinkChannel的write()方法来对其进行写入,如下所示:
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读取
要从管道读取,需要访问source channel:
Pipe.SourceChannel sourceChannel = pipe.source();
要从source channel读取,可以调用其read()方法:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);
read()方法返回的int表面已将多少字节读取到缓冲区中。
原文地址: https://www.zhblog.net/go/java/tutorial/java-nio-pipe?t=622