Home » Java NIO Pipe

Java NIO Pipe

by Online Tutorials Library

Java NIO Pipe

A Java NIO Pipe is used for establishing the one-way data connection between two threads. It has a sink channel and source channel. The data is writing to the sink channel and this data can then be read from a source channel.

In Java NIO the package java.nio.channel.pipe is used to read and write the data in a sequence. Pipe is used for ensuring that data must be read in a same order in which it is written to the Pipe.

Let’s see the block diagram illustration of Pipe operational principle:

Java Nio tutorial16


Creating a Pipe

For creating a pipe we need to open a Pipe by calling the Pipe.open() method.

The syntax used for opening or creating a Pipe is:


Reading from a Pipe

For reading the data from a Pipe we need to access the source channel. Therefore the syntax used for accessing the source channel is:

For reading the data from the SourceChannel we call the read() method as given below:

The integer value return by the read() method is used for determining the number of bytes were read into the buffer.


Writing to a Pipe

For writing the data to a Pipe we need to access the sink channel. Therefore the syntax used for accessing the sink channel is:

For writing the data to a SinkChannel we call the write() method as given below:

strong>Basic Pipe Example:

Output:

Next TopicJava NIO Charset

You may also like