当前位置:首页 > Java

java 如何下载文件

2026-02-05 02:57:27Java

使用 URL 和 HttpURLConnection 下载文件

通过 java.net.URLHttpURLConnection 建立连接,读取输入流并写入本地文件。需要处理 HTTP 响应码和异常。

URL url = new URL("http://example.com/file.zip");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    try (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);
        }
    }
} else {
    throw new IOException("Server returned non-OK status: " + responseCode);
}

使用 Apache HttpClient 下载文件

引入 Apache HttpClient 依赖(如 org.apache.httpcomponents:httpclient),通过 CloseableHttpClient 发送请求并处理响应流。

java 如何下载文件

CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("http://example.com/file.zip");

try (CloseableHttpResponse response = client.execute(request);
     InputStream inputStream = response.getEntity().getContent();
     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);
    }
}

使用 Java NIO 的 Files.copy 方法

Java 7+ 的 Files.copy 方法可直接将输入流复制到目标路径,简化代码。

java 如何下载文件

URL url = new URL("http://example.com/file.zip");
try (InputStream inputStream = url.openStream()) {
    Files.copy(inputStream, Paths.get("local_file.zip"), StandardCopyOption.REPLACE_EXISTING);
}

处理大文件下载的进度监控

通过自定义 InputStream 包装类或回调接口实现下载进度跟踪。

try (InputStream inputStream = connection.getInputStream();
     FileOutputStream outputStream = new FileOutputStream("local_file.zip")) {
    byte[] buffer = new byte[4096];
    int totalBytesRead = 0;
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
        totalBytesRead += bytesRead;
        System.out.println("Downloaded: " + totalBytesRead + " bytes");
    }
}

异步下载文件

结合 CompletableFuture 或线程池实现异步下载,避免阻塞主线程。

ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(() -> {
    URL url = new URL("http://example.com/file.zip");
    try (InputStream in = url.openStream()) {
        Files.copy(in, Paths.get("local_file.zip"));
    }
});

// 可调用 future.get() 等待下载完成

注意事项

  • 添加超时设置:通过 connection.setConnectTimeout(5000) 防止网络阻塞。
  • 关闭资源:确保 InputStreamOutputStream 和连接在 try-with-resources 中自动关闭。
  • 错误处理:检查 HTTP 状态码(如 404、503)并重试或终止。
  • 文件名处理:从 Content-Disposition 头或 URL 路径解析原始文件名。

以上方法覆盖了从基础到进阶的文件下载需求,可根据项目依赖和复杂度选择合适方案。

分享给朋友:

相关文章

vue怎么实现文件树

vue怎么实现文件树

Vue 实现文件树的方法 使用递归组件实现文件树 递归组件是Vue中实现文件树的常见方法。通过组件自身调用自身,可以处理嵌套的目录结构。 <template> <div>…

vue实现文件模板展示

vue实现文件模板展示

Vue 实现文件模板展示的方法 在 Vue 中实现文件模板展示通常涉及文件上传、预览和模板渲染等功能。以下是几种常见的实现方式。 使用文件上传组件 通过 Vue 的文件上传组件(如 el-uploa…

vue 实现文件目录

vue 实现文件目录

Vue 实现文件目录结构 Vue 项目通常采用模块化设计,合理的目录结构有助于代码维护和团队协作。以下是常见的 Vue 项目目录结构及说明: 基础目录结构(基于 Vue CLI 生成) proje…

react如何下载包

react如何下载包

使用 npm 安装 React 包 在项目目录下运行以下命令,通过 npm 安装 React 核心库和 React DOM: npm install react react-dom 使用 yarn…

php下载文件实现

php下载文件实现

PHP 下载文件实现方法 使用 header() 函数强制下载 设置合适的 HTTP 头信息,强制浏览器下载文件而非直接打开。 $file_path = '/path/to/file.pdf'; $…

vue实现文件功能

vue实现文件功能

Vue 实现文件上传功能 使用 Vue 实现文件上传功能可以通过原生 HTML 的 <input type="file"> 结合 Vue 的事件处理和 HTTP 请求库(如 Axios)来…