本文提供一個簡潔的 Java 方法,使用標準 java.net.URL 與輸入輸出流實現從網絡下載圖片並保存到本地。代碼包含目錄自動創建、緩衝讀寫、異常處理等實用細節。
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageDownloader {
/**
* 從網絡下載圖片並保存到本地
* @param imageUrl 圖片完整 URL
* @param fileName 保存的文件名(含副檔名)
* @param saveDir 保存目錄(會自動創建)
*/
public static void downloadImage(String imageUrl, String fileName, String saveDir) {
URL url = null;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
System.err.println("無效的 URL 格式: " + imageUrl);
e.printStackTrace();
return;
}
// 創建保存目錄
File dir = new File(saveDir);
if (!dir.exists()) {
boolean created = dir.mkdirs();
if (!created) {
System.err.println("無法創建目錄: " + saveDir);
return;
}
}
File outputFile = new File(dir, fileName);
try (InputStream is = url.openStream();
FileOutputStream os = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[8192]; // 8KB 緩衝區
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
System.out.println("下載成功: " + outputFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("下載失敗: " + e.getMessage());
e.printStackTrace();
}
}
// 測試主方法
public static void main(String[] args) {
String url = "https://example.com/image.jpg";
downloadImage(url, "downloaded.jpg", "d:/webimg/");
}
}
| 環節 | 實現方式 | 說明 |
|---|---|---|
| URL 解析 | new URL(string) | 拋出 MalformedURLException 需捕獲 |
| 輸入流獲取 | url.openStream() | 返回 InputStream,底層建立 HTTP 連接 |
| 目錄創建 | file.mkdirs() | 遞歸創建多級目錄 |
| 緩衝讀寫 | 8KB byte[] + read()/write() | 避免單字節讀寫效能極差 |
| 資源管理 | try-with-resources (JDK 7+) | 自動關閉流,防止洩漏 |
| 問題 | 原因 | 解決 |
|---|---|---|
| FileNotFoundException | URL 返回 404 或重定向到錯誤頁 | 檢查 URL、模擬瀏覽器 User-Agent |
| ConnectException: Connection timed out | 網路不通、防火牆、目標服務器慢 | 增加連接超時、檢查代理、換源 |
| SSLHandshakeException | HTTPS 證書驗證失敗 | 信任憑證、或跳過驗證(僅測試用) |
| 下載檔案損壞/為 0 字節 | 流未正確關閉、重定向到 HTML 頁面 | 檢查 Content-Type、確保 try-with-resources |
標準庫 java.net.URL 簡單直觀,適合輕量級下載需求。生產環境建議升級為專業 HTTP 客戶端,獲得更好的錯誤處理、效能、可觀測性與合規支援。