how to extract files from a 7-zip stream in Java without store it on hard disk?


Solution 1

Commons compress 1.6 and above has support for manipulating 7z format. Try it.

Reference :

Sample :

    SevenZFile sevenZFile = new SevenZFile(new File("test-documents.7z"));
    SevenZArchiveEntry entry = sevenZFile.getNextEntry();
        FileOutputStream out = new FileOutputStream(entry.getName());
        byte[] content = new byte[(int) entry.getSize()];, 0, content.length);
        entry = sevenZFile.getNextEntry();

Solution 2

Since 7z decompression requires random access, you'll have to read the whole stream into a byte[] and use new SevenZFile(new SeekableInMemoryByteChannel(bytes)). (If it's longer than Integer.MAX_VALUE bytes, you'll have to create a custom SeekableByteChannel implementation.) Once the instance is constructed, the process is the same as in SANN3's answer.

If it won't fit in memory and you can't write it to a temporary file, then 7zip isn't a suitable compression algorithm given its need for random access.


Related videos on Youtube

Author by


Updated on July 17, 2022


  • user3330817
    user3330817 over 1 year

    I want to extract some files from a 7-zip byte stream,it can't be stored on hard disk,so I can't use RandomAccessFile class,I have read sevenzipjbinding source code,it also uncompresses the file with some closed source things like which wrote by other language.And the method of the official package SevenZip

    SevenZip.Compression.LZMA.Decoder.Code( inStream, outStream,long outSize,ICompressProgressInfo progress)

    can only uncompress a single file.

    So how could I uncompress a 7-zip byte stream with pure Java?

    Any guys have solution?

    Sorry for my poor English and I'm waiting for your answers online.

    • MadProgrammer
      MadProgrammer almost 10 years
      Take a look at the Apache Commons, Compress library which I believe has a 7z implementation
  • user3330817
    user3330817 almost 10 years
    tips:the 7-zip byte stream is a socket stream(or http request stream),not a file stored on disk,we can't even use File class.we recently change the compress resolution to xz because 7z doesn't apply a fully-memory resolution.
  • Oleksii K.
    Oleksii K. about 8 years
    I tried Apache Commom-Compress on Android and I want to share my experience here. This solution is completely unacceptable for my goals, because it takes 3 hours (three hours) to decompress single file from 250 Mb to 750 Mb. It seems the implementation is very slow and not optimized. My phone is Nexus 5.
  • Unda
    Unda almost 8 years
    It is true that the Commons Compress library can manipulate 7z format, but apparently not from a stream, as requested by OP.