在Java中,通過URL下載文件到本地非常常見。 下面將介紹如何使用Java實現從URL下載文件到本地的操作。
一、建立URL連接並打開連接
public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//連接成功
} else {
//連接失敗
}
}
在第一步中,我們通過URL對象建立與遠程服務器的連接,並向該服務器發起一個HTTP GET請求,並且我們通過getResopnseCode()方法獲取服務器的響應狀態碼。
二、從連接中獲取輸入流並從輸入流中讀取數據
public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 獲取文件名
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// 輸出文件信息
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// 開始下載文件
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件已經下載到 " + saveFilePath + ".");
} else {
System.out.println("服務器返迴響應碼 " + responseCode);
}
}
在第二步中,我們通過輸入流從連接中讀取遠程服務器傳輸的數據。
三、將輸入流寫入本地文件
public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 獲取文件名
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// 輸出文件信息
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// 開始下載文件
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件已經下載到 " + saveFilePath + ".");
} else {
System.out.println("服務器返迴響應碼 " + responseCode);
}
}
在第三步中,我們創建一個FileStream對象並將輸入流中的數據寫入該對象。 最後,將FileStream中的數據寫入本地文件。
四、異常處理
在對下載文件進行異常處理時,我們需要考慮多種情況:
- 連接失敗
- 文件名提取失敗
- 無法獲取響應狀態碼。
為了更好地處理這些異常情況,我們需要將下載文件的實現代碼封裝成一個方法,並拋出異常。
五、完整代碼示例
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadFileUtil {
public static void downloadFileFromURL(String fileURL, String saveDir) throws IOException {
// 建立URL連接並打開連接
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
// 從連接中獲取輸入流並從輸入流中讀取數據
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// 輸出文件信息
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// 將輸入流寫入本地文件
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件已經下載到 " + saveFilePath + ".");
} else {
System.out.println("服務器返迴響應碼 " + responseCode);
}
}
}
六、總結
在Java中實現從URL下載文件到本地非常常見。到現在,您應該已經掌握了如何使用Java對文件進行下載,並成功下載文件到本地。儘管這個過程看起來很簡單,但是由於許多服務器強制使用HTTPS,所以我們需要使用Java的加密通信。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/187644.html