使用輸入輸出流複製文件後刪除源文件,結果目標文件為空,源文件也變成 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);
關鍵修正:
new File(parent, child) 構造器自動處理路徑分隔符if (destFile.length() == srcFile.length()) srcFile.delete();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;
}
}