Java Nio 简明教程

Java NIO - Pipe

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

在这两个组成通道中,一个被称为接收通道,主要用于写入数据,另一个是源通道,其主要目的是从接收通道读取数据。

在数据写入和读取期间按顺序保持数据同步,必须确保以写入管道顺序读取数据。

必须注意,管道中的数据是单向流动的,即仅写入接收通道,只能从源通道读取数据。

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

Methods of Pipe class

  1. open() − 此方法用于获取 Pipe 实例,或者我们也可以说通过调用此方法创建 pipe。

  2. sink() − 此方法返回 Pipe 的 sink 通道,此通道用于通过调用其 write 方法写入数据。

  3. source() − 此方法返回 Pipe 的 source 通道,此通道用于通过调用其 read 方法读取数据。

Example

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

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 ,其中包含以下内容。此文件将用作示例程序的输入。