Apache Commons压缩7z文件的大小比p7zip压缩大

时间:2018-08-10 19:04:10

标签: java zip compression apache-commons 7zip

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

因此,我期望使用7z将apache commons压缩也压缩到可比较的大小。但是,事实并非如此。即使我为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");
    }
}

1 个答案:

答案 0 :(得分:0)

能否请您删除这些行:

args = ['an', 'example']