java如何下载文件
使用 HttpURLConnection 下载文件
HttpURLConnection 是 Java 标准库中用于 HTTP 请求的类,适合简单的文件下载需求。
创建 URL 对象并打开连接:
URL url = new URL("http://example.com/file.zip");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
设置连接参数并获取输入流:
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputStream inputStream = connection.getInputStream();
创建输出流并写入文件:
FileOutputStream outputStream = new FileOutputStream("local_file.zip");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
关闭资源:
outputStream.close();
inputStream.close();
connection.disconnect();
使用 Apache HttpClient 下载文件
Apache HttpClient 提供更高级的 HTTP 客户端功能,适合复杂的下载场景。
添加 Maven 依赖:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
创建 HttpClient 并执行请求:
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("http://example.com/file.zip");
CloseableHttpResponse response = client.execute(request);
处理响应并保存文件:
HttpEntity entity = response.getEntity();
if (entity != null) {
try (FileOutputStream out = new FileOutputStream("local_file.zip")) {
entity.writeTo(out);
}
}
释放资源:
response.close();
client.close();
使用 Java NIO 下载文件
Java NIO 提供更高效的文件传输方式,适合大文件下载。

创建 URL 和 Path 对象:
URL url = new URL("http://example.com/file.zip");
Path path = Paths.get("local_file.zip");
使用 Files.copy 方法下载:
try (InputStream in = url.openStream()) {
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
}
处理下载进度显示
需要显示下载进度时,可以自定义输入流包装器:
class ProgressInputStream extends FilterInputStream {
private long totalRead = 0;
private final long totalSize;
protected ProgressInputStream(InputStream in, long totalSize) {
super(in);
this.totalSize = totalSize;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int bytesRead = super.read(b, off, len);
if (bytesRead > 0) {
totalRead += bytesRead;
System.out.printf("下载进度: %.2f%%%n", (totalRead * 100.0 / totalSize));
}
return bytesRead;
}
}
处理 HTTPS 下载
对于 HTTPS 下载,需要配置 SSL 上下文:
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);






