小编典典

什么是压缩/解压缩文件的好 Java 库?

all

我查看了 JDK 和 Apache 压缩库附带的默认 Zip 库,我对它们不满意有 3 个原因:

  1. 它们臃肿且 API 设计不佳。我必须自己编写 50 行样板字节数组输出、压缩输入、归档流并关闭相关流并捕获异常并移动字节缓冲区?为什么我不能有一个看起来像这样Zipper.unzip(InputStream zipFile, File targetDirectory, String password = null)并且Zipper.zip(File targetDirectory, String password = null)可以正常工作的简单 API?

  2. 似乎压缩解压缩会破坏文件元数据并且密码处理被破坏。

  3. 此外,与我使用 UNIX 获得的命令行 zip 工具相比,我尝试的所有库都慢了 2-3 倍?

对我来说 (2) 和 (3) 是次要的,但我真的想要一个经过良好测试的具有单行界面的库。


阅读 67

收藏
2022-05-13

共1个答案

小编典典

我知道它很晚并且有很多答案,但是这个zip4j是我用过的最好的压缩库之一。它简单(没有锅炉代码)并且可以轻松处理受密码保护的文件。

import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.core.ZipFile;


public static void unzip(){
    String source = "some/compressed/file.zip";
    String destination = "some/destination/folder";
    String password = "password";

    try {
         ZipFile zipFile = new ZipFile(source);
         if (zipFile.isEncrypted()) {
            zipFile.setPassword(password);
         }
         zipFile.extractAll(destination);
    } catch (ZipException e) {
        e.printStackTrace();
    }
}

Maven依赖是:

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>1.3.2</version>
</dependency>
2022-05-13