12

Possible Duplicate:
How to decompress a gzipped data in a byte array?

I have a Gzip'd byte array and I simply want to uncompress it and print the output. It's something like this:

byte[] gzip = getGZIPByteArray();

/* Code do uncompress the GZIP */

System.out.print(uncompressedGZIP);

Can anybody help me with the code in the middle?

Hash
  • 4,647
  • 5
  • 21
  • 39
vegidio
  • 822
  • 2
  • 11
  • 32

2 Answers2

19
// With 'gzip' being the compressed buffer
java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(gzip);
java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein);
java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream();

int res = 0;
byte buf[] = new byte[1024];
while (res >= 0) {
    res = gzin.read(buf, 0, buf.length);
    if (res > 0) {
        byteout.write(buf, 0, res);
    }
}
byte uncompressed[] = byteout.toByteArray();
OlivierM
  • 2,820
  • 24
  • 41
NovaDenizen
  • 5,089
  • 14
  • 28
14

The below method may give you a start :-

    public static byte[] decompress(byte[] contentBytes){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)), out);
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return out.toByteArray();
    }

Ensure that you have the below in your classpath and import them in your code.

import java.util.zip.*;
import org.apache.commons.io.IOUtils;
verisimilitude
  • 5,077
  • 3
  • 30
  • 35