Search code examples
javaandroidxz

how to use XZ lib to compress/decompress file in android


https://tukaani.org/xz/java.html This site provide a XZ Library 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.


Solution

  • I have used this library recently and this is the working code on my github link XZ compression algorithm. you can use this class in your android project. This is Main class to give the idea of how to use this class.

    public static void main(String[] args){
      String input = "Some string blah blah blah";
      System.out.println("XZ or LZMA2 library.....");
    
      // If you are using some file instead of plain text you have to 
      //convert it to bytes here and pass it to `compress` method.
    
      byte[] xzCompressed = XZ_LZMA2.compress(input);
      System.out.println("Input length:" + input.length());
      System.out.println("XZ Compressed Length: "+ xzCompressed.length);
      String xzDecompressed = XZ_LZMA2.decompress(xzCompressed);
      System.out.println("XZ Decompressed : "+ xzDecompressed);
    
      // If you are using decompression for some compressed file instead of
      // plain text return bytes from `decompress` method and put it in 
      //FileOutputStream to get file back
    }
    

    Note: XZ compression algorithm needs lots of memory to run. It's not recommended to use it for any mobile platform like Android. It will give you out of memory exception. Android provides ZLIB compression library called Deflater and Inflater. This works well on Android platform.