如何从Java中的7-zip流中提取文件而不将其存储在硬盘上?

2022-09-02 21:45:43

我想从7-zip字节流中提取一些文件,它不能存储在硬盘上,所以我不能使用RandomAccessFile类,我已经阅读了sevenzipjbinding源代码,它还解压缩了一些闭源文件,例如由其他语言编写的 lib7-Zip-JBinding.so。和官方软件包SevenZip的方法

SevenZip.Compression.LZMA.Decoder.Code(java.io.InputStream inStream,java.io.OutputStream outStream,long outSize,ICompressProgressInfo progress)

只能解压缩单个文件。

那么,如何使用纯 Java 解压缩 7 zip 字节流呢?

有人有解决方案吗?

对不起,我的英语不好,我正在等待你的在线答案。


答案 1

Commons compress 1.6 及以上版本支持操作 7z 格式。试试吧。

参考:

http://commons.apache.org/proper/commons-compress/index.html

样本:

    SevenZFile sevenZFile = new SevenZFile(new File("test-documents.7z"));
    SevenZArchiveEntry entry = sevenZFile.getNextEntry();
    while(entry!=null){
        System.out.println(entry.getName());
        FileOutputStream out = new FileOutputStream(entry.getName());
        byte[] content = new byte[(int) entry.getSize()];
        sevenZFile.read(content, 0, content.length);
        out.write(content);
        out.close();
        entry = sevenZFile.getNextEntry();
    }
    sevenZFile.close();

答案 2

由于 7z 解压缩需要随机访问,因此您必须将整个流读入 a 并使用 .(如果它比字节长,则必须创建自定义实现。构建实例后,该过程与 SANN3 的答案中的过程相同。byte[]new SevenZFile(new SeekableInMemoryByteChannel(bytes))Integer.MAX_VALUESeekableByteChannel

如果它不适合内存,并且您无法将其写入临时文件,则7zip不是合适的压缩算法,因为它需要随机访问。


推荐