Java NIO - 管道



在 Java NIO 中,管道是一個用於在兩個執行緒之間寫入和讀取資料的元件。管道主要由兩個負責資料傳播的通道組成。

在兩個組成通道中,一個稱為接收通道,主要用於寫入資料;另一個稱為源通道,其主要目的是從接收通道讀取資料。

在資料寫入和讀取過程中保持資料同步,必須確保資料讀取的順序與寫入管道的順序相同。

必須注意,管道中的資料流是單向的,即資料只能寫入接收通道,並且只能從源通道讀取。

在 Java NIO 中,管道被定義為一個抽象類,其中主要有三個方法,其中兩個是抽象的。

管道類的的方法

  • open() − 此方法用於獲取管道例項,或者我們可以說透過呼叫此方法建立管道。

  • sink() − 此方法返回管道的接收通道,該通道透過呼叫其寫入方法來寫入資料。

  • source() − 此方法返回管道的源通道,該通道透過呼叫其讀取方法來讀取資料。

示例

以下示例演示了 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();
      }
   }
}

輸出

Test Data to Check java NIO Channels Pipe.

假設我們有一個文字檔案c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入。

廣告