Java 从服务器下载文件到本地
在 Java 中,有几种常见的方法可以从服务器下载文件到本地,以下是几种实现方式:

使用 Java 原生 HTTPURLConnection
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
connection.disconnect();
}
public static void main(String[] args) {
String fileUrl = "http://example.com/path/to/file.zip";
String savePath = "C:/downloads/file.zip";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功: " + savePath);
} catch (IOException e) {
System.err.println("文件下载失败: " + e.getMessage());
}
}
}
使用 Apache HttpClient (更强大和灵活)
首先添加依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
然后使用以下代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
public class HttpClientDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(new HttpGet(fileUrl))) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream in = entity.getContent();
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/path/to/file.zip";
String savePath = "C:/downloads/file.zip";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功: " + savePath);
} catch (IOException e) {
System.err.println("文件下载失败: " + e.getMessage());
}
}
}
使用 Java NIO (适用于大文件)
import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class NioDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fileUrl))
.build();
HttpResponse<InputStream> response = client.send(request,
HttpResponse.BodyHandlers.ofInputStream());
Path destination = Paths.get(savePath);
Files.copy(response.body(), destination);
}
public static void main(String[] args) {
String fileUrl = "http://example.com/path/to/file.zip";
String savePath = "C:/downloads/file.zip";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功: " + savePath);
} catch (IOException | InterruptedException e) {
System.err.println("文件下载失败: " + e.getMessage());
}
}
}
带进度显示的下载
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class ProgressDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
int fileSize = connection.getContentLength();
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
int progress = (int) (totalBytesRead * 100 / fileSize);
System.out.printf("下载进度: %d%%\n", progress);
}
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/path/to/file.zip";
String savePath = "C:/downloads/file.zip";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功: " + savePath);
} catch (IOException e) {
System.err.println("文件下载失败: " + e.getMessage());
}
}
}
注意事项
- 错误处理:实际应用中应添加更完善的错误处理
- 大文件处理:对于大文件,考虑使用缓冲区和NIO
- 认证:如果服务器需要认证,需要添加相应的认证头
- 超时设置:建议设置连接超时和读取超时
- 断点续传:如果需要支持断点续传,需要处理Range头
- 多线程下载:对于大文件,可以考虑分块多线程下载
方法可以根据你的具体需求和环境选择使用。

