Java实现文件下载功能
在Java中,我们可以使用java.net包中的URL和HttpURLConnection类来实现文件的下载,以下是一个简单的示例:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownload {
public static void main(String[] args) {
String fileURL = "http://example.com/file.zip"; // 文件URL
String saveDir = "/Users/username/Downloads"; // 保存目录
try {
downloadFile(fileURL, saveDir);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void downloadFile(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// 确保HTTP响应代码为200(HTTP_OK)
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// 如果Content-Disposition头字段存在,从其中获取文件名
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// 如果Content-Disposition头字段不存在,从URL中获取文件名
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// 打开输入流并读取数据
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// 打开输出流并将数据写入文件
OutputStream 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("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
这个程序首先创建一个URL对象,然后使用这个URL对象打开一个HttpURLConnection,它检查HTTP响应代码是否为200(HTTP_OK),如果是,它将从HTTP响应头中获取文件名,并从输入流中读取数据,然后将数据写入到输出流中,最后关闭输入流和输出流,如果HTTP响应代码不是200,它将打印一条错误消息。



还没有评论,来说两句吧...