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

Android 文件移動失敗且源文件變空的問題排查與修正

     編輯:程式設計綜合問答

問題現象

使用輸入輸出流複製文件後刪除源文件,結果目標文件為空,源文件也變成 0 位元組。

根本原因

代碼中 File desfile = new File(newPath); 僅建立目標資料夾,但寫入流使用 desfile.getAbsolutePath() + name 時,若 newPath 未以分隔符結尾,會導致路徑錯誤(如 /sdcard/DCIMphoto.jpg 而非 /sdcard/DCIM/photo.jpg),實際寫入一個名為 DCIMphoto.jpg 的文件而非預期目錄下的文件。

修正方案

File destFile = new File(newPath, name); // 正確構建目標文件
OutputStream os = new FileOutputStream(destFile);

關鍵修正:

  1. 使用 new File(parent, child) 構造器自動處理路徑分隔符
  2. 刪除源文件前驗證目標文件大小:if (destFile.length() == srcFile.length()) srcFile.delete();
  3. 使用 Files.move() (API 26+) 實現原子移動

完整修正代碼片段

public static boolean moveFile(String srcPath, String destDir, String fileName) {
    File srcFile = new File(srcPath);
    File destDirFile = new File(destDir);
    if (!destDirFile.exists()) destDirFile.mkdirs();
    File destFile = new File(destDirFile, fileName);
    try (InputStream is = new FileInputStream(srcFile);
         OutputStream os = new FileOutputStream(destFile)) {
        byte[] buffer = new byte[8192];
        int length;
        while ((length = is.read(buffer)) > 0) os.write(buffer, 0, length);
        return srcFile.delete(); // 僅複製成功後刪除
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved