首页 > 解决方案 > Apache commons 压缩 7z 文件的大小比 p7zip 压缩要大

问题描述

当我压缩 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");
    }
}

标签: javazipcompressionapache-commons7zip

解决方案


您能否尝试删除这些行:

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);

推荐阅读