Inflates (un-DEFLATE) the specified compressed byte array data. - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Inflates (un-DEFLATE) the specified compressed byte array data.

Demo Code

/**/*from   w ww.j  a  v a2  s.  co m*/
 * Copyright (c) 2010 Martin Geisse
 *
 * This file is distributed under the terms of the MIT license.
 */
import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] compressedData = new byte[]{34,35,36,37,37,37,67,68,69};
        byte[] dictionary = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(inflate(compressedData,dictionary)));
    }
    /**
     * Inflates (un-DEFLATEs) the specified compressed data.
     * @param compressedData the compressed data
     * @param dictionary the dictionary, or null if none
     * @return the uncompressed data
     */
    public static byte[] inflate(byte[] compressedData, byte[] dictionary) {
        // TODO the documentation for Inflater "expects a dummy byte" -- this seems to mean that
        // compressedData should be one byte longer than the input. Check if it works anyway;
        // Comment from Mark Adler on SO: "The current versions of zlib don't need it. I'm not
        // sure what version of zlib is used by java.util.zip."
        Inflater inflater = new Inflater(true);
        if (dictionary != null) {
            inflater.setDictionary(dictionary);
        }
        inflater.setInput(compressedData);
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[256];
            while (!inflater.finished()) {
                int n = inflater.inflate(buffer);
                byteArrayOutputStream.write(buffer, 0, n);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (DataFormatException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials