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

关键点

java 如何解压文件

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

使用 Apache Commons Compress 库

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

Maven 依赖

java 如何解压文件

<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

如何安装java

下载Java开发工具包(JDK) 访问Oracle官方网站或OpenJDK下载页面,选择适合操作系统的版本(Windows、macOS或Linux)。推荐下载最新的长期支持(LTS)版本,如Java…

如何自学java

如何自学java

选择合适的学习资源 从官方文档开始,Oracle提供的Java官方教程(Java Tutorials)是权威且免费的学习资料。在线平台如Codecademy、Coursera或Udemy提供互动式课程…

java如何创建类

java如何创建类

创建类的基本语法 在Java中,类通过class关键字定义,语法如下: [访问修饰符] class 类名 { // 成员变量(属性) // 构造方法 // 成员方法 }…

java如何产生随机数

java如何产生随机数

使用 Math.random() 方法 Math.random() 生成一个范围在 [0.0, 1.0) 的伪随机 double 值。通过缩放和偏移可以生成指定范围的随机数。 double ra…

java中如何输入

java中如何输入

输入方法 在Java中,可以通过多种方式实现输入操作,具体取决于输入来源和需求。以下是几种常见的输入方法: 使用Scanner类 Scanner类是Java中最常用的输入工具,适用于从控制台或文件读…

如何阅读java源码

如何阅读java源码

阅读Java源码的方法 选择合适的源码项目 初学者建议从JDK核心类库(如java.lang、java.util)或知名开源项目(如Spring、Guava)入手。选择文档完善、社区活跃的项目能降低理…