首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java NIO FileChannel transferFrom 複製檔案大小為 0 的解決

     編輯:程式設計疑難解答

使用 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() 前來源檔案已完全寫入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved