Use java gzip to uncompress input content - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Use java gzip to uncompress input content

Demo Code


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] compressedContent = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(ungzip(compressedContent)));
    }/*from   w  ww. j ava2  s .  c  o m*/
    /**
     * Log4j logger
     */
    static Logger logger = Logger.getLogger(CompressUtil.class);
    /**
     * Use java gzip to uncompress input content
     * 
     * @param compressedContent
     * @return null if IOException occurs
     */
    public static byte[] ungzip(byte[] compressedContent) {
        byte[] content = null;
        if (compressedContent == null)
            return content;
        ByteArrayInputStream bais = new ByteArrayInputStream(
                compressedContent);
        try {
            GZIPInputStream gzipStream = new GZIPInputStream(bais);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            int i;
            while ((i = gzipStream.read(buffer)) != -1) {
                baos.write(buffer, 0, i);
            }
            content = baos.toByteArray();

            gzipStream.close();
            bais.close();
            baos.close();
        } catch (IOException e) {
            logger.warn("ungzip error: " + e.getMessage(), e);
        }
        return content;
    }
}

Related Tutorials