Java Deflate Byte Array deflateByteArray(final byte[] array)

Here you can find the source of deflateByteArray(final byte[] array)

Description

Deflates the file and returns the deflated file.

License

Open Source License

Parameter

Parameter Description
array the array of bytes to be deflated

Exception

Parameter Description
IOException if problems were experienced.

Return

a compressed (deflated) array of bytes

Declaration

public static byte[] deflateByteArray(final byte[] array) throws IOException 

Method Source Code

//package com.java2s;
/*/*from   www .j ava  2s .c o  m*/
 * Copyright (c) 2003 Stephan D. Cote' - All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which accompanies this distribution, and is
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote
 *      - Initial API and implementation
 */

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.zip.Deflater;

public class Main {
    private static final int ZIP_BUFFER_SIZE = 50;

    /**
     * Deflates the file and returns the deflated file.
     * 
     * <p>This is useful for compressing the contents of a single file or data 
     * field. Some use it as an obfuscation tactic, encoding a string to bytes,
     * deflating it and converting to Base64.
     *
     * @param array the array of bytes to be deflated
     *
     * @return a compressed (deflated) array of bytes
     *
     * @throws IOException if problems were experienced.
     */
    public static byte[] deflateByteArray(final byte[] array) throws IOException {
        byte[] retval = null;
        final Deflater deflater = new Deflater(Deflater.DEFLATED, false);
        deflater.setInput(array);
        deflater.finish();

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            while (!deflater.finished()) {
                final byte[] data = new byte[ZIP_BUFFER_SIZE];
                final int count = deflater.deflate(data);

                if (count == data.length) {
                    baos.write(data);
                } else {
                    baos.write(data, 0, count);
                }
            }

            deflater.end();

            retval = baos.toByteArray();
        } finally {
            baos.close();
        }

        return retval;
    }
}

Related

  1. deflate(byte[] input)
  2. deflate(final byte[] pInput)
  3. deflate(String inString)
  4. deflate(String text, String encode)
  5. deflateBuffer(byte[] uncompressedBuffer)
  6. deflateGzip(byte[] inputBytes)
  7. deflateGzip(final byte[] bts)
  8. deflater(final byte[] inputByte)