Java NIO Pipe

来源:互联网 发布:人工智能威胁论 提出人 编辑:程序博客网 时间:2024/05/16 07:35


Java Nio 

1Java NIO Tutorial2Java NIO Overview3Java NIO Channel4Java NIO Buffer5Java NIO Scatter / Gather6Java NIO Channel to Channel Transfers7Java NIO Selector8Java NIO FileChannel9Java NIO SocketChannel10Java NIO ServerSocketChannel11Java NIO DatagramChannel12Java NIO Pipe13Java NIO vs. IO

Java NIO Pipe

 
By Jakob Jenkov
 Connect with me: 
Rate article:
Share article:
Tweet

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 InternalsJava 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.







0 1