Java的NIO之不同channel之間傳輸資料__java

來源:互聯網
上載者:User
5.不同通道channel之間傳輸資料

在Java的NIO中,如果兩個通道中有一個是FileChannel,那麼我們可以直接將資料從一個channel傳輸到另外一個channel中。兩個通道之間傳輸資料的方式有兩種,分別是:
- transferFrom()
- transferTo() 5.1 transferFrom()

FileChannel 的transferFrom()方法可以將資料從源通道傳輸到FileChannel中(這個方法在JDK文檔中解釋為將位元組從給定的可讀取位元組通道傳輸到此通道的檔案中)。下面是一個簡單的例子:

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");FileChannel fromChannel = fromFile.getChannel();//擷取source的通道;RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");FileChannel toChannel = toFile.getChannel();//擷取dest的通道;long position = 0;long count = fromChannel.size();long result = toChannel.transferFrom(fromChannel, position, count);LogUtil.log_debug(""+result);

方法的輸入參數
- position表示從position處開始向目標檔案寫入資料,
- count表示最多傳輸的位元組數。如果源通道的剩餘空間小於count個位元組,則所傳輸的位元組數要小於請求的位元組數。

此外要注意,在SoketChannel的實現中,SocketChannel只會傳輸此刻準備好的資料(可能不足count位元組)。因此,SocketChannel可能不會將請求的所有資料(count個位元組)全部傳輸到FileChannel中。 5.2 transferTo()方法

transferTo()方法將資料從FileChannel傳輸到其他的channel中。下面是一個簡單的例子:

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");FileChannel fromChannel = fromFile.getChannel();//擷取source的通道;RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");FileChannel toChannel = toFile.getChannel();//擷取dest的通道;long position = 0;long count = fromChannel.size();long result = fromChannel.transferTo(position, count, toChannel);LogUtil.log_debug(""+result);

觀察一下就可以發現,其實這兩個例子其實非常的相似,如果僅僅從檔案IO的角度來看,就是兩個檔案之間的資料複製;

上面所說的關於SocketChannel的問題在transferTo()方法中同樣存在。SocketChannel會一直傳輸資料直到目標buffer被填滿。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.