網路上許多資源(如電子書、教學影片、資料集)會被拆分成成百上千個小檔案,手動逐一下載不僅繁瑣,更幾乎不可能完成。幸好這些檔案命名通常遵循規律(如 chapter001.zip、chapter002.zip...),我們可以編寫程式自動化下載整個序列。
InputStream。FileOutputStream 存檔。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());
企業環境常需透過 Proxy 存取外網:
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "10.154.134.110");
System.getProperties().put("proxyPort", "8080");
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);
}
}
}
}
RandomAccessFile 實作。Java 提供豐富的網路與 IO API,讓我們能快速建構功能完善的下載工具。掌握 URL、HttpURLConnection、串流處理與多執行緒技巧,即可應對大多數批量下載需求。