How to use LZMA SDK to compress/decompress in Java

lamwaiman1988 picture lamwaiman1988 · Mar 30, 2011 · Viewed 38.8k times · Source

http://www.7-zip.org/sdk.html This site provide a LZMA SDK for compress/decompress files, I would like to give it a shot but I am lost.

Anyone got experience on this? Or a tutorial? Thanks.

Answer

Stefano Fratini picture Stefano Fratini · Feb 8, 2012

Short answer: don't

The 7zip sdk is old and unmaintained and it's just a JNI wrapper around the C++ library. A pure Java implementation on a modern JVM (1.7+) is as fast as a C++ one and has less dependecies and portability issues.

Have a look at http://tukaani.org/xz/java.html

XZ is a file format based on LZMA2 (an improved version of LZMA)

The guys that invented the XZ format build a pure java implementation of the XZ archive compression / extraction algorithms

The XZ file format is designed to store 1 file only. Thus you need to zip/tar the source folder(s) into a single uncompressed file first.

Using the java library is as easy as this:

FileInputStream inFile = new FileInputStream("src.tar");
FileOutputStream outfile = new FileOutputStream("src.tar.xz");

LZMA2Options options = new LZMA2Options();

options.setPreset(7); // play with this number: 6 is default but 7 works better for mid sized archives ( > 8mb)

XZOutputStream out = new XZOutputStream(outfile, options);

byte[] buf = new byte[8192];
int size;
while ((size = inFile.read(buf)) != -1)
   out.write(buf, 0, size);

out.finish();