当前位置:首页 > 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 包含 ../ 路径),需对输出路径做校验:

java 如何解压文件

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

如何打开java

打开 Java 程序的方法 通过命令行运行 Java 程序 确保已安装 Java Development Kit (JDK) 并配置环境变量。使用 javac 编译 .java 文件,生成 .clas…

如何删除java

如何删除java

卸载 Java 的步骤 Windows 系统: 打开控制面板,选择“程序和功能”或“卸载程序”,在列表中找到 Java 相关条目(如“Java Runtime Environment”或“Java D…

java如何调用接口

java如何调用接口

调用接口的基本方法 在Java中调用接口通常涉及实现接口或使用接口引用对象。以下是几种常见场景的示例: 定义接口 public interface MyInterface { void d…

java前景如何

java前景如何

Java 当前的市场需求 Java 在企业级开发、大数据、云计算等领域仍占据重要地位。许多大型企业(如银行、电商平台)依赖 Java 构建后端系统。招聘平台数据显示,Java 开发岗位数量稳定,尤其在…

java如何连接数据库

java如何连接数据库

Java连接数据库的方法 Java连接数据库通常使用JDBC(Java Database Connectivity)技术,以下是具体步骤和示例代码。 加载数据库驱动 在连接数据库之前,需要加载对应的…

如何编写java

如何编写java

编写Java程序的基本步骤 安装Java开发工具包(JDK),确保系统环境变量配置正确。可以从Oracle官网下载最新版本的JDK并进行安装。 选择一个合适的集成开发环境(IDE),如Eclipse…