使用 FileChannel.transferFrom 複製檔案時,若目標通道對應的 RandomAccessFile 開啟模式錯誤,會導致複製出的檔案大小為 0。關鍵在於輸入與輸出通道必須分別綁定來源與目標檔案。
RandomAccessFile raf = new RandomAccessFile(src, "rw");
FileChannel from = raf.getChannel();
RandomAccessFile raf1 = new RandomAccessFile(dest, "rw");
FileChannel to = raf.getChannel(); // 錯誤:重複使用來源通道
to.transferFrom(from, 0, from.size());
RandomAccessFile raf = new RandomAccessFile(src, "r");
FileChannel from = raf.getChannel();
RandomAccessFile raf1 = new RandomAccessFile(dest, "rw");
FileChannel to = raf1.getChannel(); // 正確:使用目標檔案通道
to.transferFrom(from, 0, from.size());
// 關閉順序:先通道後檔案
from.close(); to.close(); raf.close(); raf1.close();
"r" 唯讀模式即可,目標檔案需 "rw" 讀寫模式。transferFrom 是零複製操作,效率極高,適合大檔案傳輸。size() 前來源檔案已完全寫入。