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

Java 字節流複製圖片失敗:路徑轉義、異常處理、資源關閉三大坑

     編輯:程式設計疑難解答

原代碼問題

fos = new FileOutputStream("D:\畢向東視頻\9.png"); // \9 被轉義為制表符!
fis = new FileInputStream("D:\畢向東視頻\99.png");

三大修正

  1. 路徑轉義:Windows 路徑用雙反斜杠 `D:\\...` 或正斜杠 `D:/...`。
  2. 異常打印堆棧:`throw new RuntimeException("複製失敗", e);` 保留原始異常信息。
  3. try-with-resources 確保關閉(Java 7+):
    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");

驗證

  • 檢查目標文件大小與源文件一致。
  • 圖片查看器能正常打開。
  • MD5 校驗:`MessageDigest.getInstance("MD5")` 對比。

總結

路徑轉義是 Java 文件操作第一坑,配合 try-with-resources 與完整異常鏈,複製圖片零失誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved