Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decompressing to a byte[] using GzipInputStream

I have a class that compresses and decompresses a byte array;

public class Compressor
{
    public static byte[] compress(final byte[] input) throws IOException
    {
        try (ByteArrayOutputStream bout = new ByteArrayOutputStream();
                GZIPOutputStream gzipper = new GZIPOutputStream(bout))
        {
            gzipper.write(input, 0, input.length);
            gzipper.close();

            return bout.toByteArray();
        }
    }

    public static byte[] decompress(final byte[] input) throws IOException
    {
        try (ByteArrayInputStream bin = new ByteArrayInputStream(input);
                GZIPInputStream gzipper = new GZIPInputStream(bin))
        {
            // Not sure where to go here
        }
    }
}

How do I decompress the input and return a byte array?

Note: I don't want to do any conversion to strings because of character encoding issues.

like image 500
Joshua Kissoon Avatar asked May 12 '14 09:05

Joshua Kissoon


1 Answers

your missing code will be something like

byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();

int len;
while ((len = gzipper.read(buffer)) > 0) {
    out.write(buffer, 0, len);
}

gzipper.close();
out.close();
return out.toByteArray();
like image 181
Leo Avatar answered Oct 06 '22 23:10

Leo