decompress byte array in GZIP - Java File Path IO

Java examples for File Path IO:GZIP

Description

decompress byte array in GZIP

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.zip.GZIPInputStream;

public class Main {
    public static String decompress(byte[] compressed) throws IOException {
        byte[] h = new byte[2];
        h[0] = (compressed)[0];/*from   w  w w .j  a v  a2 s .com*/
        h[1] = (compressed)[1];
        int head = getShort(h);
        boolean t = head == 0x1f8b;
        InputStream in = null;
        StringBuilder sb = new StringBuilder();
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
            if (t) {
                in = new GZIPInputStream(bis);
            } else {
                in = bis;
            }
            BufferedReader r = new BufferedReader(
                    new InputStreamReader(in), 1000);
            for (String line = r.readLine(); line != null; line = r
                    .readLine()) {
                sb.append(line);
            }
            r.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return sb.toString();
    }

    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }
}

Related Tutorials