java - Apache commons 压缩 7z 文件大小比 p7zip 压缩大得多

标签 java zip compression apache-commons 7zip

当我压缩 500mb 的 html 文件时,p7zip 在几秒钟内完成,文件大小为 7mb(没有任何自定义设置,只需 7z a filename.7z/folder)。

因此,我期望 apache commons compress 也使用 7z 压缩到相当的大小。然而,事实并非如此。即使我启用了 apache commons compress 7z 的最大预设。生成的文件大小也很大,接近 100mb。

我做错了什么或者我需要调整我的预设吗?我已阅读 apache commons compress wiki 但尚未找到我的答案。

java实现的相关代码:

public static Path compress(String name, List<Path> files) throws IOException {
    try (SevenZOutputFile out = new SevenZOutputFile(new File(name))) {
        List<SevenZMethodConfiguration> methods = new ArrayList<>();


        LZMA2Options lzma2Options = new LZMA2Options();
        lzma2Options.setPreset(LZMA2Options.PRESET_MAX);
        SevenZMethodConfiguration lzmaConfig =
                new SevenZMethodConfiguration(SevenZMethod.LZMA, lzma2Options);
        methods.add(lzmaConfig);
        out.setContentMethods(methods);

        for (Path file : files) {
            addToArchiveCompression(out, file, ".");
        }
    }

    return Paths.get(name);
}


private static void addToArchiveCompression(SevenZOutputFile out, Path file,
                                            String dir) throws IOException {
    String name = dir + File.separator + file.getFileName();
    if (Files.isRegularFile(file)) {
        SevenZArchiveEntry entry = out.createArchiveEntry(file.toFile(), name);
        out.putArchiveEntry(entry);

        FileInputStream in = new FileInputStream(file.toFile());
        byte[] b = new byte[1024];
        int count = 0;
        while ((count = in.read(b)) > 0) {
            out.write(b, 0, count);
        }
        out.closeArchiveEntry();

    } else if (Files.isDirectory(file)) {
        File[] children = file.toFile().listFiles();
        if (children != null) {
            for (File child : children) {
                addToArchiveCompression(out, Paths.get(child.toURI()), name);
            }
        }
    } else {
        System.out.println(file.getFileName() + " is not supported");
    }
}

最佳答案

您能否尝试删除这些行:

List<SevenZMethodConfiguration> methods = new ArrayList<>();

LZMA2Options lzma2Options = new LZMA2Options();
lzma2Options.setPreset(LZMA2Options.PRESET_MAX);
SevenZMethodConfiguration lzmaConfig =
        new SevenZMethodConfiguration(SevenZMethod.LZMA, lzma2Options);
methods.add(lzmaConfig);
out.setContentMethods(methods);

关于java - Apache commons 压缩 7z 文件大小比 p7zip 压缩大得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792678/

相关文章:

java - 安全 Web 服务异常 : This service requires <wsse:Security>, 缺失

python - 我必须压缩许多相似的文件,我可以利用它们相似的事实吗?

javascript - 括号表示法可以用来压缩/混淆 JavaScript 吗?

javascript - 在 Javascript 中压缩 Guid

android - 如果 Tomcat7 服务器具有 GZIP 压缩,Android 客户端将如何?

java - 在 Oracle JDBC 客户端中指定密码哈希而不是清除密码

java - Java 循环中的变量

java - 为什么编译器/JVM 不能将自动装箱设置为 "just work"?

javascript - React - 从字节字符串中的 API 响应正文下载 Zip 文件?

Java-我们可以压缩本地数据库并使用 EmbeddedDriver 连接存档吗