当前位置:首页 > Java

java如何下载zip文件

2026-03-03 19:19:43Java

使用 Java 下载 ZIP 文件的方法

使用 java.net.URLjava.nio.file

从 URL 下载 ZIP 文件并保存到本地路径,可以使用 java.net.URLjava.nio.file 类。以下是示例代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class DownloadZipFile {
    public static void downloadFile(String fileURL, String savePath) throws IOException {
        URL url = new URL(fileURL);
        try (InputStream in = url.openStream()) {
            Path targetPath = Path.of(savePath);
            Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
        }
    }

    public static void main(String[] args) {
        String fileURL = "https://example.com/file.zip";
        String savePath = "downloaded_file.zip";

        try {
            downloadFile(fileURL, savePath);
            System.out.println("File downloaded successfully.");
        } catch (IOException e) {
            System.err.println("Error downloading file: " + e.getMessage());
        }
    }
}

使用 Apache HttpClient

如果需要更高级的功能(如处理重定向或 HTTP 认证),可以使用 Apache HttpClient:

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.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DownloadZipWithHttpClient {
    public static void downloadFile(String fileURL, String savePath) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(fileURL);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try (InputStream in = entity.getContent();
                         FileOutputStream out = new FileOutputStream(savePath)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        String fileURL = "https://example.com/file.zip";
        String savePath = "downloaded_file.zip";

        try {
            downloadFile(fileURL, savePath);
            System.out.println("File downloaded successfully.");
        } catch (IOException e) {
            System.err.println("Error downloading file: " + e.getMessage());
        }
    }
}

使用 Java 11+ 的 HttpClient

Java 11 引入了新的 HttpClient API,可以更简洁地实现下载:

java如何下载zip文件

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class DownloadZipWithJava11HttpClient {
    public static void downloadFile(String fileURL, String savePath) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileURL))
                .build();

        HttpResponse<Path> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofFile(
                        Path.of(savePath),
                        StandardOpenOption.CREATE,
                        StandardOpenOption.WRITE
                )
        );

        if (response.statusCode() == 200) {
            System.out.println("File downloaded successfully.");
        } else {
            System.err.println("Failed to download file: HTTP " + response.statusCode());
        }
    }

    public static void main(String[] args) {
        String fileURL = "https://example.com/file.zip";
        String savePath = "downloaded_file.zip";

        try {
            downloadFile(fileURL, savePath);
        } catch (Exception e) {
            System.err.println("Error downloading file: " + e.getMessage());
        }
    }
}

注意事项

  • 确保目标 URL 支持直接下载 ZIP 文件。
  • 检查文件权限和磁盘空间是否足够。
  • 对于大文件,建议使用缓冲流以提高效率。
  • 添加适当的异常处理(如网络超时或文件写入失败)。

分享给朋友:

相关文章

vue实现文件的上传

vue实现文件的上传

文件上传的基本实现 在Vue中实现文件上传通常结合HTML的<input type="file">元素和FormData对象。通过监听文件选择事件获取文件对象,再通过AJAX或axios发…

vue实现文件对比

vue实现文件对比

Vue实现文件对比的方法 使用第三方库实现差异对比 推荐使用diff-match-patch或jsdiff库,它们专为文本差异对比设计,支持高亮显示差异部分。安装后可直接在Vue组件中调用。…

vue中实现文件导入

vue中实现文件导入

文件导入的基本实现 在Vue中实现文件导入通常通过HTML的<input type="file">元素结合Vue的事件处理完成。创建一个文件选择按钮,监听change事件获取用户选择的文件…

vue实现文件电子签名

vue实现文件电子签名

实现文件电子签名的基本步骤 安装依赖库 需要使用signature_pad库实现手写签名功能,通过npm或yarn安装: npm install signature_pad # 或 yarn add…

如何下载react库

如何下载react库

使用 npm 安装 React 通过 npm(Node.js 包管理器)可以快速安装 React。确保已安装 Node.js,然后在项目目录中运行以下命令: npm install react re…

react如何调用打开文件

react如何调用打开文件

使用 input 元素触发文件选择 在 React 中可以通过创建一个隐藏的 input 元素并设置其 type 为 file。当用户点击自定义按钮时,通过 ref 触发该 input 的点击事件。…