首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實作 HTTP 檔案佇列下載器:從基礎到完整程式碼

     編輯:Java 相關知識

前言:批量下載的痛點

網路上許多資源(如電子書、教學影片、資料集)會被拆分成成百上千個小檔案,手動逐一下載不僅繁瑣,更幾乎不可能完成。幸好這些檔案命名通常遵循規律(如 chapter001.zip、chapter002.zip...),我們可以編寫程式自動化下載整個序列。

核心流程三步驟

  1. 發起連線:客戶端對目標 URL 發起 HTTP 請求。
  2. 取得輸入串流:伺服器解析 URL,回傳資源的 InputStream。
  3. 寫入本地檔案:客戶端讀取串流內容,以 FileOutputStream 存檔。

關鍵技術點

1. 基礎網路連線 (java.net)

String destUrl = "https://www.example.com/file001.zip";
URL url = new URL(destUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.connect();
BufferedInputStream bis = new BufferedInputStream(httpConn.getInputStream());

2. 代理伺服器設定

企業環境常需透過 Proxy 存取外網:

System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "10.154.134.110");
System.getProperties().put("proxyPort", "8080");

3. 檔案儲存邏輯

FileOutputStream fos = new FileOutputStream(fileName);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
    fos.write(buffer, 0, bytesRead);
}
fos.close();
bis.close();

完整下載器類別設計

封裝 HttpGet 類別,支援佇列式批量下載:

  • 使用 Vector 維護下載 URL 清單與對應檔名。
  • 提供 addItem(url, filename) 加入任務。
  • downLoadByList() 依序執行下載,含例外處理與除錯輸出。
public class HttpGet {
    private static final int BUFFER_SIZE = 8192;
    private final Vector urlList = new Vector<>();
    private final Vector fileList = new Vector<>();

    public void addItem(String url, String filename) {
        urlList.add(url);
        fileList.add(filename);
    }

    public void downLoadByList() {
        for (int i = 0; i < urlList.size(); i++) {
            try {
                saveToFile(urlList.get(i), fileList.get(i));
            } catch (IOException e) {
                System.err.println("下載失敗: " + urlList.get(i) + " - " + e.getMessage());
            }
        }
    }

    private void saveToFile(String urlStr, String fileName) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        try (BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
             FileOutputStream fos = new FileOutputStream(fileName)) {
            byte[] buf = new byte[BUFFER_SIZE];
            int len;
            while ((len = bis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
        }
    }
}

擴展建議

  • 斷點續傳:利用 HTTP Range 標頭與 RandomAccessFile 實作。
  • 多執行緒下載:將單一檔案分段並行下載,或併發處理多個檔案。
  • 進度條與狀態回呼:整合 Swing/JavaFX UI 或 Logging 框架。
  • 健壯性:加入重試機制、超時設定、校驗和(MD5/SHA)。

總結

Java 提供豐富的網路與 IO API,讓我們能快速建構功能完善的下載工具。掌握 URL、HttpURLConnection、串流處理與多執行緒技巧,即可應對大多數批量下載需求。

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