Compresses data using zlib compression. - Java File Path IO

Java examples for File Path IO:Zip File

Description

Compresses data using zlib compression.

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        int len = 2;
        System.out.println(java.util.Arrays.toString(deflateData(data,
                offset, len)));/*from w w  w .  j a  v  a 2 s .co m*/
    }

    /**
     * Compresses data using zlib compression. Uses default compression settings.
     * 
     * @param data
     *            The data to be compressed.
     * @return The compressed data.
     */
    public static byte[] deflateData(byte[] data, int offset, int len) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream(
                data.length);
        byte[] buffer = new byte[data.length];
        Deflater def = new Deflater();

        def.setInput(data, offset, len);
        def.finish();

        while (!def.finished()) {
            int d = def.deflate(buffer);
            stream.write(buffer, 0, d);
        }

        return stream.toByteArray();
    }
}

Related Tutorials