
- Java NIO 教程
- Java NIO - 首頁
- Java NIO - 概述
- Java NIO - 環境設定
- Java NIO vs JAVA IO
- Java NIO - 通道(Channels)
- Java NIO - 檔案通道(File Channel)
- Java NIO - 資料報通道(DataGram Channel)
- Java NIO - 套接字通道(Socket Channel)
- Java NIO - 伺服器套接字通道(Server Socket Channel)
- Java NIO - 分散(Scatter)
- Java NIO - 收集(Gather)
- Java NIO - 緩衝區(Buffer)
- Java NIO - 選擇器(Selector)
- Java NIO - 管道(Pipe)
- Java NIO - 路徑(Path)
- Java NIO - 檔案(File)
- Java NIO - 非同步檔案通道(AsynchronousFileChannel)
- Java NIO - 字元集(CharSet)
- Java NIO - 檔案鎖(FileLock)
- Java NIO 有用資源
- Java NIO - 快速指南
- Java NIO - 有用資源
- Java NIO - 討論
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 中引入分散/收集方法是一種經過最佳化的多工方法(如果使用得當)。它允許您將將讀取的資料分成多個塊的分離工作委託給作業系統,或將不同的資料塊組合成一個整體。毫無疑問,這節省了時間,並透過避免緩衝區複製更有效地利用作業系統,並減少了需要編寫和除錯的程式碼量。
廣告