当前位置:首页 > 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 是一个更强大的选择。

java如何下载zip文件

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,可以更简洁地实现下载功能。

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

分享给朋友:

相关文章

css文件怎么制作

css文件怎么制作

创建CSS文件的基本步骤 CSS文件用于定义网页的样式,可以与HTML文件分离,便于管理和维护。以下是创建CSS文件的方法: 新建文本文件 使用任意文本编辑器(如Notepad++、VS Code、…

如何编译java文件

如何编译java文件

安装JDK 确保系统已安装Java Development Kit(JDK)。可通过命令行输入 javac -version 和 java -version 验证。若未安装,需从Oracle或Open…

php实现文件下载代码

php实现文件下载代码

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

js实现文件的上传

js实现文件的上传

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。HTML部分需要包含一个文件选择控件和一个提交按…

vue实现文件分享

vue实现文件分享

Vue 实现文件分享功能 前端文件上传与展示 使用 Vue 和 Element UI 实现文件上传组件,允许用户选择文件并上传到服务器。 <template> <div>…

vue实现文件进度

vue实现文件进度

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