閱讀24 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java NIO係列教程(五) 通道之間的數據傳輸

在Java NIO中,如果兩個通道中有一個是FileChannel,那你可以直接將數據從一個channel(譯者注:channel中文常譯作通道)傳輸到另外一個channel。

transferFrom()

FileChannel的transferFrom()方法可以將數據從源通道傳輸到FileChannel中(譯者注:這個方法在JDK文檔中的解釋為將字節從給定的可讀取字節通道傳輸到此通道的文件中)。下麵是一個簡單的例子:

01 RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
02 FileChannel      fromChannel = fromFile.getChannel();
03  
04 RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
05 FileChannel      toChannel = toFile.getChannel();
06  
07 long position = 0;
08 long count = fromChannel.size();
09  
10 toChannel.transferFrom(position, count, fromChannel);

方法的輸入參數position表示從position處開始向目標文件寫入數據,count表示最多傳輸的字節數。如果源通道的剩餘空間小於 count 個字節,則所傳輸的字節數要小於請求的字節數。
此外要注意,在SoketChannel的實現中,SocketChannel隻會傳輸此刻準備好的數據(可能不足count字節)。因此,SocketChannel可能不會將請求的所有數據(count個字節)全部傳輸到FileChannel中。

transferTo()

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

01 RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
02 FileChannel      fromChannel = fromFile.getChannel();
03  
04 RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
05 FileChannel      toChannel = toFile.getChannel();
06  
07 long position = 0;
08 long count = fromChannel.size();
09  
10 fromChannel.transferTo(position, count, toChannel);

是不是發現這個例子和前麵那個例子特別相似?除了調用方法的FileChannel對象不一樣外,其他的都一樣。
上麵所說的關於SocketChannel的問題在transferTo()方法中同樣存在。SocketChannel會一直傳輸數據直到目標buffer被填滿。


文章轉自 並發編程網-ifeve.com

最後更新:2017-05-22 17:31:37

  上一篇:go  Java NIO係列教程(四) Scatter/Gather
  下一篇:go  Java NIO係列教程(九) ServerSocketChannel