Java NIO管道是两个线程之间的单向数据链接。Pipe
具备源信道和接受通道。您将数据写入sink通道。而后能够从源通道读取该数据。spa
这是一个原理的Pipe流程图
:线程
![]() |
Java NIO:Pipe Internals |
建立管道
你打开一个Pipe
经过调用该Pipe.open()
方法。code
代码:blog
Pipe pipe = Pipe.open();
向管写入信息
要写入Pipe
你须要访问接收器通道。ip
代码:字符串
Pipe.SinkChannel sinkChannel = pipe.sink();
经过SinkChannel调用write()
方法来写,get
代码:it
String newData =“要写入文件的新字符串...”+ System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()){ sinkChannel.write(BUF); }
从管道读取数据
要从中读取,Pipe
您须要访问源通道。pip
代码:table
Pipe.SourceChannel sourceChannel = pipe.source();
要从源通道读取,调用read()
方法:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);
read()
方法返回的int值,代表向缓冲区中读取多少个字节。