標籤:att locate message [] 一個 get channel img rom
http://wiki.jikexueyuan.com/project/java-nio-zh/java-nio-scatter-gather.html
05. Java NIO Scatter / Gather
Scattering read指的是從通道讀取的操作能把資料寫入多個buffer,也就是sctters代表了資料從一個channel到多個buffer的過程。
gathering write則正好相反,表示的是從多個buffer把資料寫入到一個channel中。
Scatter/gather在有些情境下會非常有用,比如需要處理多份分開傳輸的資料。舉例來說,假設一個訊息包含了header和body,我們可能會把header和body儲存在不同獨立buffer中,這種分開處理header與body的做法會使開發更簡明。
ByteBuffer header = ByteBuffer.allocate(128);ByteBuffer body = ByteBuffer.allocate(1024);ByteBuffer[] bufferArray = { header, body };channel.read(bufferArray);//必須寫滿一個buffer後才會向後移動到下一個buffer,適合header大小固定的讀取
Gathering Writes
ByteBuffer header = ByteBuffer.allocate(128);ByteBuffer body = ByteBuffer.allocate(1024);//write data into buffersByteBuffer[] bufferArray = { header, body };channel.write(bufferArray);//按順序將數組內的內容寫進channel,寫入buffer中position到limit之間的資料,適用於可變大小的message06. Java NIO Channel to Channel Transfers通道傳輸介面
在Java NIO中如果一個channel是FileChannel類型的,利用FileChannel包含的transferTo和transferFrom兩個方法,可以直接把資料轉送到另一個channel。
FileChannel.transferFrom方法把資料從通道源傳輸到FileChannel:
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");FileChannel fromChannel = fromFile.getChannel();RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");FileChannel toChannel = toFile.getChannel();long position = 0;long count = fromChannel.size();toChannel.transferFrom(fromChannel, position, count);
transferFrom的參數position和count表示目標檔案的寫入位置和最多寫入的資料量。如果通道源的資料小於count那麼就傳實際有的資料量。 另外,有些SocketChannel的實現在傳輸時只會傳輸哪些處於就緒狀態的資料,即使SocketChannel後續會有更多可用資料。因此,這個傳輸過程可能不會傳輸整個的資料。
transferTo方法把FileChannel資料轉送到另一個channel
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");FileChannel fromChannel = fromFile.getChannel();RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");FileChannel toChannel = toFile.getChannel();long position = 0;long count = fromChannel.size();fromChannel.transferTo(position, count, toChannel);
這段代碼和之前介紹transfer時的代碼非常相似,區別只在於調用方法的是哪個FileChannel.
SocketChannel的問題也存在與transferTo.SocketChannel的實現可能只在發送的buffer填充滿後才發送,並結束。
Java NIO(二)