当前位置:首页 > 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());
        }
    }
}

处理大文件下载

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

java如何下载zip文件

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. 考虑添加重试机制应对网络不稳定情况

分享给朋友:

相关文章

vue实现文件进度

vue实现文件进度

Vue 实现文件上传进度 使用 Vue 实现文件上传进度可以通过结合 axios 或原生 XMLHttpRequest 的进度事件来实现。以下是两种常见方法: 使用 axios 上传文件并显…

vue实现word文件预览

vue实现word文件预览

vue实现word文件预览的方法 在Vue项目中实现Word文件预览,可以通过以下几种方式: 使用mammoth.js库 mammoth.js是一个将.docx文件转换为HTML的JavaScrip…

vue文件下载实现方式

vue文件下载实现方式

vue文件下载实现方式 使用a标签下载 通过创建a标签并设置download属性实现文件下载。适用于已知文件URL或Blob对象的情况。 // 方法1: 直接使用URL const down…

如何启动react文件

如何启动react文件

启动 React 项目的步骤 确保已安装 Node.js 和 npm 在启动 React 项目之前,需确保系统已安装 Node.js(包含 npm)。可以通过以下命令检查是否安装成功: node -…

如何下载react库

如何下载react库

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

react  如何创建文件

react 如何创建文件

创建 React 文件的基本方法 在 React 项目中,创建文件通常涉及组件文件、样式文件或工具文件。以下是常见操作方式: 手动创建文件 通过文件资源管理器或 IDE(如 VSCode)在项目目录…