6 Java NIO Channel to Channel Transfers-翻譯

王金龍發表於2017-12-06

在Java NIO中,如果其中的一個通道是FileChannel,你可以直接從一個通道向另一個通道直接轉換資料。FileChannel有一個transferTo和transferFrom方法來實現這個功能。

transferFrom()

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);
複製程式碼

引數position和count分別表明目標檔案從哪裡開始寫,最大需要轉換的位元組數。如果源channel的長度小於count,則取小的那個。

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

transferTo()

transferTo方法負責將FileChannel轉換到其他Channel.下面是一個簡單的例子。

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt","rw");
FileChannel fromChannel = fromFile.getChannle();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt","rw");
FileChannel  toChannel = toFile.getChannel();

long position = 0;
long count = fromChannel.size();

fromChannel.transferTo(position,count,toChannel);

複製程式碼

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

相關文章