gzip byte array - Java File Path IO

Java examples for File Path IO:GZIP

Description

gzip byte array

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.util.zip.GZIPOutputStream;

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

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

        GZIPOutputStream gos = null;

        try {//w ww .  j  ava2s.  c om
            gos = new GZIPOutputStream(os);

            int count = 0;
            byte data[] = new byte[BUFFER];
            while ((count = is.read(data, 0, BUFFER)) != -1) {
                gos.write(data, 0, count);
            }

            gos.finish();
            gos.flush();
        } finally {
            closeQuietly(gos);
        }
    }

    public static byte[] gzip(byte[] bytes) throws IOException {
        ByteArrayOutputStream baOut = null;
        GZIPOutputStream gzOut = null;
        try {
            baOut = new ByteArrayOutputStream();
            gzOut = new GZIPOutputStream(baOut);
            gzOut.write(bytes);
            gzOut.finish();
            gzOut.flush();
            return baOut.toByteArray();
        } finally {
            closeQuietly(gzOut);
            closeQuietly(baOut);
        }
    }

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

Related Tutorials