gunzip InputStream - Java File Path IO

Java examples for File Path IO:GZIP

Description

gunzip InputStream

Demo Code


//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.util.zip.GZIPInputStream;

public class Main {
    public static final int BUFFER = 4096;

    public static void gunzip(InputStream is, OutputStream os)
            throws IOException {

        GZIPInputStream gis = null;
        try {/*from ww w  .  j a  va  2 s.c o m*/
            gis = new GZIPInputStream(is);
            int count = 0;
            byte data[] = new byte[BUFFER];
            while ((count = gis.read(data, 0, BUFFER)) != -1) {
                os.write(data, 0, count);
            }

        } finally {
            closeQuietly(gis);
        }

    }

    public static byte[] gunzip(byte[] bytes) throws IOException {

        ByteArrayOutputStream baOut = null;
        ByteArrayInputStream baIn = null;
        GZIPInputStream gzIn = null;
        try {
            baOut = new ByteArrayOutputStream();
            baIn = new ByteArrayInputStream(bytes);
            gzIn = new GZIPInputStream(baIn);
            int count = 0;
            byte data[] = new byte[BUFFER];
            while ((count = gzIn.read(data, 0, BUFFER)) != -1) {
                baOut.write(data, 0, count);
            }

            return baOut.toByteArray();
        } finally {
            closeQuietly(gzIn);
            closeQuietly(baIn);
            closeQuietly(baOut);
        }
    }

    public static void closeQuietly(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials