Java NIO Pipe

Posted winner-0715

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java NIO Pipe相关的知识,希望对你有一定的参考价值。

A Java NIO Pipe is a one-way data connection between two threads. A Pipe has a source channel and a sink channel. You write data to the sink channel. This data can then be read from the source channel.

Here is an illustration of the Pipe principle:

技术分享图片
Java NIO: Pipe Internals

Creating a Pipe

You open a Pipe by calling the Pipe.open() method. Here is how that looks:

Pipe pipe = Pipe.open();

Writing to a Pipe

To write to a Pipe you need to access the sink channel. Here is how that is done:

Pipe.SinkChannel sinkChannel = pipe.sink();

You write to a SinkChannel by calling it‘s write() method, like this:

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);
}

Reading from a Pipe

To read from a Pipe you need to access the source channel. Here is how that is done:

Pipe.SourceChannel sourceChannel = pipe.source();

To read from the source channel you call its read() method like this:

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

The int returned by the read() method tells how many bytes were read into the buffer.

 

以上是关于Java NIO Pipe的主要内容,如果未能解决你的问题,请参考以下文章

Java NIO -- 管道 (Pipe)

Java NIO系列教程 Pipe

java NIO之Pipe

转:Java NIO系列教程 Pipe

Java NIO系列教程 Pipe

Java NIO系列教程 Pipe