在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的加密通信。