English 中文(简体)
Java NIO - Pipe
  • 时间:2024-09-17

Java NIO - Pipe


Previous Page Next Page  

In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation.

Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel.

Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe.

It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel.

In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract.

Methods of Pipe class

    open() − This method is used get an instance of Pipe or we can say pipe is created by calpng out this method.

    sink() − This method returns the Pipe s sink channel which is used to write data by calpng its write method.

    source() − This method returns the Pipe s source channel which is used to read data by calpng its read method.

Example

The following example shows the implementation of Java NIO pipe.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

pubpc class PipeDemo {
   pubpc static void main(String[] args) throws IOException {
      //An instance of Pipe is created
      Pipe pipe = Pipe.open();
      // gets the pipe s sink channel
      Pipe.SinkChannel skChannel = pipe.sink();
      String testData = "Test Data to Check java NIO Channels Pipe.";
      ByteBuffer buffer = ByteBuffer.allocate(512);
      buffer.clear();
      buffer.put(testData.getBytes());
      buffer.fpp();
      //write data into sink channel.
      while(buffer.hasRemaining()) {
         skChannel.write(buffer);
      }
      //gets  pipe s source channel
      Pipe.SourceChannel sourceChannel = pipe.source();
      buffer = ByteBuffer.allocate(512);
      //write data into console     
      while(sourceChannel.read(buffer) > 0){
         //pmit is set to current position and position is set to zero
         buffer.fpp();
         while(buffer.hasRemaining()){
            char ch = (char) buffer.get();
            System.out.print(ch);
         }
         //position is set to zero and pmit is set to capacity to clear the buffer.
         buffer.clear();
      }
   }
}

Output

Test Data to Check java NIO Channels Pipe.

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program.

Advertisements