GZIP a byte array - Java java.lang

Java examples for java.lang:byte Array Compress

Description

GZIP a byte array

Demo Code


//package com.java2s;
import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] src = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(gzip(src)));
    }/*from www .  j  a  v  a2  s  .  c  o  m*/

    /**
     * GZIP a byte array
     */
    public static byte[] gzip(byte[] src) throws IOException {

        InputStream is = null;
        ByteArrayOutputStream os = null;
        GZIPOutputStream zipOut = null;

        try {

            is = new ByteArrayInputStream(src);
            os = new ByteArrayOutputStream(src.length);
            zipOut = new GZIPOutputStream(os);

            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                zipOut.write(buf, 0, len);
            }
            is.close();

            // Complete the GZIP file
            zipOut.finish();
            zipOut.close();

            return os.toByteArray();

        } finally {
            if (null != os) {
                os.close();
            }
            is = null;
            os = null;
            zipOut = null;
        }
    }

    /**
     * Print a byte array as a String
     */
    public static String toString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(4 * bytes.length);
        sb.append("[");

        for (int i = 0; i < bytes.length; i++) {
            sb.append(unsignedByteToInt(bytes[i]));
            if (i + 1 < bytes.length) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    /**
     * Convert an unsigned byte to an int
     */
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }
}

Related Tutorials