当前位置:首页 > Java

java如何下载zip文件

2026-02-05 08:06:00Java

使用 Java 下载 ZIP 文件

使用 java.net.URLjava.nio.file 下载 ZIP 文件

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DownloadZipFile {
    public static void downloadFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        Path path = Paths.get(savePath);

        try (BufferedInputStream in = new BufferedInputStream(url.openStream());
             FileOutputStream out = new FileOutputStream(path.toFile())) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer, 0, 1024)) != -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());
        }
    }
}

使用 Apache HttpClient 下载 ZIP 文件

如果项目允许使用第三方库,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.IOException;
import java.io.InputStream;

public class DownloadZipWithHttpClient {
    public static void downloadFile(String fileUrl, String savePath) throws IOException {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(fileUrl);
            try (CloseableHttpResponse response = client.execute(request)) {
                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 = "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 下载 ZIP 文件

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

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.Paths;
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();

        Path path = Paths.get(savePath);
        client.send(request, HttpResponse.BodyHandlers.ofFile(path, StandardOpenOption.CREATE));
    }

    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 (Exception e) {
            System.err.println("Error downloading file: " + e.getMessage());
        }
    }
}

处理大文件下载

对于大文件下载,可以显示下载进度。

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.text.DecimalFormat;

public class DownloadWithProgress {
    public static void downloadFile(String fileUrl, String savePath) throws Exception {
        URL url = new URL(fileUrl);
        long fileSize = url.openConnection().getContentLengthLong();

        try (BufferedInputStream in = new BufferedInputStream(url.openStream());
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            long totalRead = 0;
            DecimalFormat df = new DecimalFormat("0.00");

            while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, bytesRead);
                totalRead += bytesRead;
                double progress = (totalRead * 100.0) / fileSize;
                System.out.print("\rDownload progress: " + df.format(progress) + "%");
            }
            System.out.println("\nDownload completed.");
        }
    }

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

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

注意事项

  1. 确保目标目录有写入权限
  2. 处理网络连接异常和文件系统异常
  3. 对于 HTTPS 连接,可能需要配置 SSL 证书
  4. 大文件下载时考虑内存使用情况
  5. 可能需要设置超时时间防止长时间阻塞
  6. 考虑添加重试机制应对网络不稳定情况

java如何下载zip文件

分享给朋友:

相关文章

vue实现文件模板展示

vue实现文件模板展示

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

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

实现.vue文件

实现.vue文件

创建Vue单文件组件 Vue单文件组件(.vue文件)是Vue.js框架的核心特性之一,它将模板、脚本和样式封装在一个文件中。一个典型的.vue文件结构包含三个部分:<template>、…

php下载文件实现

php下载文件实现

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

php实现文件下载代码

php实现文件下载代码

实现文件下载的基本方法 使用PHP实现文件下载的核心是通过设置HTTP头部信息,强制浏览器触发下载行为而非直接显示文件内容。 $file_path = 'path/to/your/file.ext…

vue实现搜索文件

vue实现搜索文件

Vue 实现搜索文件功能 在 Vue 中实现文件搜索功能,可以通过以下步骤完成。这里假设文件数据存储在本地或通过 API 获取。 数据准备 确保有一个文件列表数据,可以是静态数据或从后端 API 获…