Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**
     * Compresses a GZIP file.
     * 
     * @param bytes
     *            The uncompressed bytes.
     * @return The compressed bytes.
     * @throws IOException
     *             if an I/O error occurs.
     */
    public static byte[] gzip(byte[] bytes) throws IOException {
        /* create the streams */
        InputStream is = new ByteArrayInputStream(bytes);
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            OutputStream os = new GZIPOutputStream(bout);
            try {
                /* copy data between the streams */
                byte[] buf = new byte[4096];
                int len = 0;
                while ((len = is.read(buf, 0, buf.length)) != -1) {
                    os.write(buf, 0, len);
                }
            } finally {
                os.close();
            }

            /* return the compressed bytes */
            return bout.toByteArray();
        } finally {
            is.close();
        }
    }
}