当前位置:首页 > Java

java 如何解压文件

2026-03-03 19:13:40Java

使用 java.util.zip 包解压文件

Java 内置的 java.util.zip 包提供了处理 ZIP 文件的工具类。以下是一个完整的解压示例:

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipExample {
    public static void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry = zipIn.getNextEntry();
            while (entry != null) {
                String filePath = destDirectory + File.separator + entry.getName();
                if (!entry.isDirectory()) {
                    extractFile(zipIn, filePath);
                } else {
                    File dir = new File(filePath);
                    dir.mkdir();
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }
        }
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
            byte[] bytesIn = new byte[4096];
            int read;
            while ((read = zipIn.read(bytesIn)) != -1) {
                bos.write(bytesIn, 0, read);
            }
        }
    }

    public static void main(String[] args) {
        try {
            unzip("example.zip", "output_folder");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

关键点

  • 使用 ZipInputStream 读取 ZIP 文件条目。
  • 检查条目是否为目录,非目录时调用 extractFile 写入文件。
  • 缓冲区大小(4096)可根据需求调整。

使用 Apache Commons Compress 库

对于更复杂的压缩格式(如 TAR、7z),推荐使用 Apache Commons Compress 库。

Maven 依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.25.0</version>
</dependency>

解压 ZIP 示例

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import java.io.*;

public class CommonsUnzip {
    public static void unzip(String zipFile, String outputDir) throws IOException {
        try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipFile))) {
            ZipArchiveEntry entry;
            while ((entry = zis.getNextZipEntry()) != null) {
                File outputFile = new File(outputDir, entry.getName());
                if (entry.isDirectory()) {
                    outputFile.mkdirs();
                } else {
                    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            os.write(buffer, 0, len);
                        }
                    }
                }
            }
        }
    }
}

处理路径安全

为避免 ZIP 路径遍历漏洞(如恶意 ZIP 包含 ../ 路径),需对输出路径做校验:

String canonicalDestPath = destDir.getCanonicalPath() + File.separator;
String canonicalEntryPath = new File(destDir, entry.getName()).getCanonicalPath();
if (!canonicalEntryPath.startsWith(canonicalDestPath)) {
    throw new IOException("ZIP entry试图跳出目标目录: " + entry.getName());
}

其他格式支持

  • GZIP:使用 GZIPInputStream 解压单个 .gz 文件。
  • TAR:结合 TarArchiveInputStream(需 Commons Compress)。
// GZIP 解压示例
try (GZIPInputStream gis = new GZIPInputStream(new FileInputStream("file.gz"));
     FileOutputStream fos = new FileOutputStream("output.txt")) {
    byte[] buffer = new byte[1024];
    int len;
    while ((len = gis.read(buffer)) > 0) {
        fos.write(buffer, 0, len);
    }
}

通过以上方法,可以灵活处理常见压缩文件的解压需求。

java 如何解压文件

标签: 文件java
分享给朋友:

相关文章

vue实现文件的上传

vue实现文件的上传

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

java如何使用

java如何使用

Java 基本使用方法 Java 是一种广泛使用的编程语言,适用于开发各种类型的应用程序。以下是 Java 的基本使用方法,包括环境配置、语法基础和常用操作。 安装 Java 开发环境 下载并安装…

实现.vue文件

实现.vue文件

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

jquery文件

jquery文件

jQuery文件获取与使用 jQuery是一个快速、简洁的JavaScript库,简化了HTML文档遍历、事件处理、动画和Ajax交互。以下是获取和使用jQuery文件的方法。 下载jQuery文…

如何学好java

如何学好java

理解基础概念 掌握Java的核心概念是学习的基础。包括数据类型、变量、运算符、控制流(如循环和条件语句)、数组等。理解面向对象编程(OOP)的四大特性:封装、继承、多态和抽象。 实践编程练习 通过…

java如何连接mysql

java如何连接mysql

连接 MySQL 数据库的基本步骤 添加 MySQL 驱动依赖 在项目中引入 MySQL 的 JDBC 驱动。如果使用 Maven,在 pom.xml 中添加以下依赖: <dependency…