Javaでバイト列をgzip/gunzipしてみる

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


class Test {
    public static void main(String[] args) {
        try {
            String s = "abc";
            byte[] gz = gzip(s.getBytes());
            byte[] bytes = gunzip(gz);
            String s2 = new String(bytes);

            System.out.println(s2);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static byte[] gzip(byte[] bytes) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip_out = new GZIPOutputStream(out);
        gzip_out.write(bytes);
        gzip_out.close();
        out.close();
        byte[] ret = out.toByteArray();
        return ret;
    }
    
    private static byte[] gunzip(byte[] gzip_bytes) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(gzip_bytes);
        GZIPInputStream gzip_in = new GZIPInputStream(in);
        int len;
        byte[] buffer = new byte[1024];
        while ((len = gzip_in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }       
        gzip_in.close();
        in.close();
        out.close();
        byte[] ret = out.toByteArray();
        return ret;
    }
}