Java Zip Byte Array zip(byte[] in)

Here you can find the source of zip(byte[] in)

Description

Returns an gzipped copy of the input array.

License

Apache License

Declaration

public static final byte[] zip(byte[] in) 

Method Source Code

//package com.java2s;
/**/*from  ww  w.  j  a va 2  s  .c  o m*/
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.zip.GZIPOutputStream;

public class Main {
    private static final int EXPECTED_COMPRESSION_RATIO = 5;

    /**
     * Returns an gzipped copy of the input array.
     */
    public static final byte[] zip(byte[] in) {
        try {
            // compress using GZIPOutputStream 
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);

            GZIPOutputStream outStream = new GZIPOutputStream(byteOut);

            try {
                outStream.write(in);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return byteOut.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. doZip(byte[] data)
  2. zip(byte[] bytes)
  3. zip(byte[] data)
  4. zip(byte[] datas)
  5. zip(byte[] input)
  6. zip(byte[] input)
  7. zip(byte[] source)
  8. zip(byte[] uncompressedBytes)