Java Nio 简明教程

Java NIO - Pipe

在 Java NIO 中,管道是一个用于在两个线程之间写入和读取数据的组件。管道主要由负责数据传播的两个通道组成。

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.

在 Java NIO 中,管道被定义为一个抽象类,主要有三个方法,其中两个是抽象的。

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

Methods of Pipe class

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

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

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

Example

以下示例显示 Java NIO 管道实现。

The following example shows the implementation of Java NIO pipe.

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

public class PipeDemo {
   public 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.flip();
      //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){
         //limit is set to current position and position is set to zero
         buffer.flip();
         while(buffer.hasRemaining()){
            char ch = (char) buffer.get();
            System.out.print(ch);
         }
         //position is set to zero and limit is set to capacity to clear the buffer.
         buffer.clear();
      }
   }
}

Output

Test Data to Check java NIO Channels Pipe.

假设我们有一个文本文件 c:/test.txt ,其中包含以下内容。此文件将用作示例程序的输入。

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.