Deflate the specified input byte array data. - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Deflate the specified input byte array data.

Demo Code

/**/*from  www  .ja  v a 2s.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[] data = 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(deflate(data,dictionary)));
    }
    /**
     * DEFLATEs the specified input data.
     * 
     * @param data the input data
     * @param dictionary the dictionary, or null if none
     * @return the compressed data
     */
    public static byte[] deflate(byte[] data, byte[] dictionary) {
        Deflater deflater = new Deflater(8, true);
        if (dictionary != null) {
            deflater.setDictionary(dictionary);
        }
        deflater.setInput(data);
        deflater.finish();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        while (!deflater.finished()) {
            int n = deflater.deflate(buffer);
            byteArrayOutputStream.write(buffer, 0, n);
        }
        byte[] result = byteArrayOutputStream.toByteArray();
        return result;
    }
}

Related Tutorials