Java NIO - 收集(Gather)



眾所周知,與傳統的 Java IO API 相比,Java NIO 是一個更最佳化的資料 IO 操作 API。Java NIO 提供的另一個額外支援是從多個緩衝區讀取/寫入資料到通道。這種多重讀寫支援被稱為分散和收集,其中在讀取資料時,資料從單個通道分散到多個緩衝區,而在寫入資料時,資料從多個緩衝區收集到單個通道。

為了實現從通道進行這種多重讀寫,Java NIO 提供了 ScatteringByteChannel 和 GatheringByteChannel API 來讀取和寫入資料,如下例所示。

GatheringByteChannel(收集位元組通道)

寫入多個通道 - 在這裡,我們將資料從多個緩衝區寫入單個通道。為此,將分配多個緩衝區並將其新增到緩衝區型別陣列中。然後,將此陣列作為引數傳遞給 GatheringByteChannel write() 方法,該方法隨後按緩衝區在陣列中出現的順序從多個緩衝區寫入資料。這裡需要注意的是,只有緩衝區位置和限制之間的資料才會被寫入。

以下示例演示瞭如何在 Java NIO 中執行資料收集。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;

public class GatherExample {
   private static String FILENAME = "C:/Test/temp.txt";
   public static void main(String[] args) {
      String stream1 = "Gather data stream first";
      String stream2 = "Gather data stream second";
      ByteBuffer bLen1 = ByteBuffer.allocate(1024);
      ByteBuffer bLen2 = ByteBuffer.allocate(1024);
      // Next two buffer hold the data we want to write
      ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes());
      ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes());
      int len1 = stream1.length();
      int len2 = stream2.length();
      // Writing length(data) to the Buffer
      bLen1.asIntBuffer().put(len1);
      bLen2.asIntBuffer().put(len2);
      System.out.println("Gathering : Len1 = " + len1);
      System.out.println("Gathering : Len2 = " + len2);
      // Write data to the file
      try { 
         FileOutputStream out = new FileOutputStream(FILENAME);
         GatheringByteChannel gather = out.getChannel();						
         gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2});
         out.close();
         gather.close();
      }
      catch (FileNotFoundException exObj) {
         exObj.printStackTrace();
      }
      catch(IOException ioObj) {
         ioObj.printStackTrace();
      }
   }
}

輸出

Gathering : Len1 = 24
Gathering : Len2 = 25

最後,可以得出結論,在 Java NIO 中引入分散/收集方法是一種經過最佳化的多工方法(如果使用得當)。它允許您將將讀取的資料分成多個塊的分離工作委託給作業系統,或將不同的資料塊組合成一個整體。毫無疑問,這節省了時間,並透過避免緩衝區複製更有效地利用作業系統,並減少了需要編寫和除錯的程式碼量。

廣告