Java NIO学习笔记八 Pipe

Java NIO Pipe

  Java NIO管道是两个线程之间的单向数据连接。Pipe 具有源信道和接受通道。您将数据写入sink通道。然后可以从源通道读取该数据。

这是一个原理的Pipe流程图

Java NIO:管内部
Java NIO:Pipe Internals

创建管道

你打开一个Pipe通过调用该Pipe.open()方法。

代码:

Pipe pipe = Pipe.open();

向管写入信息

要写入Pipe你需要访问接收器通道。

代码:

Pipe.SinkChannel sinkChannel = pipe.sink();

通过SinkChannel调用write() 方法来写,

代码:

String newData =“要写入文件的新字符串...”+ System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()){
    sinkChannel.write(BUF);
}

从管道读取数据

要从中读取,Pipe您需要访问源通道。

代码:

Pipe.SourceChannel sourceChannel = pipe.source();

要从源通道读取,调用read()方法:

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

read()方法返回的int值,表明向缓冲区中读取多少个字节。

原文地址:https://www.cnblogs.com/kuoAT/p/7019039.html