Java tutorial
//package com.java2s; //License from project: Open Source License 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 */ try (InputStream is = new ByteArrayInputStream(bytes)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (OutputStream os = new GZIPOutputStream(bout)) { /* copy data between the streams */ byte[] buf = new byte[4096]; int len; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } /* return the compressed bytes */ return bout.toByteArray(); } } }