Gunzip a byte array - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Gunzip a byte array

Demo Code


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

import java.util.zip.GZIPInputStream;

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(gunzip(src)));
    }/*from   ww w .j  av a 2 s.  c o m*/

    /**
     * Gunzip a byte array
     */
    public static byte[] gunzip(byte[] src) throws IOException {

        InputStream is = null;
        ByteArrayOutputStream os = null;
        GZIPInputStream zipIn = null;

        try {

            is = new ByteArrayInputStream(src);
            zipIn = new GZIPInputStream(is);

            os = new ByteArrayOutputStream(src.length * 2);

            int len;
            byte[] buf = new byte[1024];

            while ((len = zipIn.read(buf, 0, 1024)) > 0) {
                os.write(buf, 0, len);
            }

            // close streams
            is.close();
            os.close();

            return os.toByteArray();

        } finally {

            if (null != os) {
                os.close();
            }
            is = null;
            os = null;
            zipIn = 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