Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncompress a GZIP string in Java [duplicate]

Tags:

java

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?

like image 728
vegidio Avatar asked Sep 21 '12 13:09

vegidio


2 Answers

// 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();
like image 91
NovaDenizen Avatar answered Oct 07 '22 10:10

NovaDenizen


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;
like image 21
verisimilitude Avatar answered Oct 07 '22 11:10

verisimilitude