fos = new FileOutputStream("D:\畢向東視頻\9.png"); // \9 被轉義為制表符!
fis = new FileInputStream("D:\畢向東視頻\99.png");
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buf = new byte[8192];
int len;
while ((len = fis.read(buf)) != -1) fos.write(buf, 0, len);
} // 自動關閉
public static void copyImage(String srcPath, String destPath) {
try (FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath)) {
byte[] buf = new byte[8192];
int len;
while ((len = fis.read(buf)) != -1) fos.write(buf, 0, len);
System.out.println("複製成功:" + destPath);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("複製失敗: " + e.getMessage(), e);
}
}
// 調用
copyImage("D:/畢向東視頻/99.png", "D:/畢向東視頻/9.png");
路徑轉義是 Java 文件操作第一坑,配合 try-with-resources 與完整異常鏈,複製圖片零失誤。