在Java NIO中,如果兩個通道中有一個是FileChannel,那你可以直接將數(shù)據(jù)從一個channel傳輸?shù)搅硗庖粋€channel咽块。
RandomAccessFile fromFile =newRandomAccessFile("fromFile.txt","rw");
FileChannel????? fromChannel = fromFile.getChannel();
RandomAccessFile toFile =newRandomAccessFile("toFile.txt","rw");
FileChannel????? toChannel = toFile.getChannel();
longposition =0;
longcount = fromChannel.size();
toChannel.transferFrom(position, count, fromChannel);
方法的輸入?yún)?shù)position表示從position處開始向目標文件寫入數(shù)據(jù)潮剪,count表示最多傳輸?shù)淖止?jié)數(shù)。如果源通道的剩余空間小于 count 個字節(jié)袁稽,則所傳輸?shù)淖止?jié)數(shù)要小于請求的字節(jié)數(shù)勿璃。
RandomAccessFile fromFile =newRandomAccessFile("fromFile.txt","rw");
FileChannel????? fromChannel = fromFile.getChannel();
RandomAccessFile toFile =newRandomAccessFile("toFile.txt","rw");
FileChannel????? toChannel = toFile.getChannel();
long position =0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);
transferTo()方法將數(shù)據(jù)從FileChannel傳輸?shù)狡渌腸hannel中