Java NIO(二)

來源:互聯網
上載者:User

標籤: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之間的資料,適用於可變大小的message
06. 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(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.