Compress byte array using Deflater/Inflater method - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Compress byte array using Deflater/Inflater method

Demo Code


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Key;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] data = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(compress(data)));
    }/*from w w  w .  jav  a 2 s .c  om*/
    private static final String ALGO = "AES";
    private static final byte[] keyValue = "Ad0#2s!3oGyRq!5F".getBytes();
    /**
     * Compress byte array using Deflater/Inflater method
     * @param data
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static byte[] compress(byte[] data) throws IOException,
            Exception {
        Deflater deflater = new Deflater();
        deflater.setLevel(Deflater.BEST_COMPRESSION);
        deflater.setInput(data);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                data.length);

        deflater.finish();
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer); // returns the generated code... index
            outputStream.write(buffer, 0, count);
        }
        outputStream.close();
        byte[] output = outputStream.toByteArray();

        output = encrypt(output);

        return output;
    }
    /**
     * Encrypt byte array using AES algorithm
     * @param Data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data);
        //String encryptedValue = new BASE64Encoder().encode(encVal);
        return encVal;
    }
    private static Key generateKey() throws Exception {
        if (key == null)
            key = new SecretKeySpec(keyValue, ALGO);

        return key;
    }
}

Related Tutorials