Compress a byte array using ZLIB compression - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Compress a byte array using ZLIB compression

Demo Code

// Permission is hereby granted, free of charge, to any person obtaining a
//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.util.zip.Deflater;

public class Main {
    /**//  w w w  .j a  va2 s  .c om
     * Compress a byte array using ZLIB compression
     * 
     * @param uncompressedData
     *            byte array of uncompressed data
     * @return byte array of compressed data
     */
    public static byte[] compressBytes(byte[] uncompressedData) {
        // Create the compressor with highest level of compression
        Deflater compressor = new Deflater();
        compressor.setLevel(Deflater.BEST_COMPRESSION);

        // Give the compressor the data to compress
        compressor.setInput(uncompressedData);
        compressor.finish();

        // Create an expandable byte array to hold the compressed data.
        // You cannot use an array that's the same size as the orginal because
        // there is no guarantee that the compressed data will be smaller than
        // the uncompressed data.
        ByteArrayOutputStream bos = new ByteArrayOutputStream(
                uncompressedData.length);

        // Compress the data
        byte[] buf = new byte[1024];
        while (!compressor.finished()) {
            int count = compressor.deflate(buf);
            bos.write(buf, 0, count);
        }
        try {
            bos.close();
        } catch (IOException e) {
        }

        // Get the compressed data
        byte[] compressedData = bos.toByteArray();
        return compressedData;
    }
}

Related Tutorials