compress byte array by level - Java java.lang

Java examples for java.lang:byte Array Compress

Description

compress byte array by level

Demo Code


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

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 level = 2;
        System.out// www .j a v  a2s  . c  o  m
                .println(java.util.Arrays.toString(compress(data, level)));
    }

    public final static int BUFFER_SIZE = 4092;

    public static byte[] compress(byte[] data, int level)
            throws IOException {
        if (data == null || data.length == 0) {
            return data;
        }
        ByteArrayOutputStream bout = new ByteArrayOutputStream(data.length);
        Deflater deflater = new Deflater();
        deflater.setLevel(level);
        deflater.setInput(data);
        deflater.finish();
        byte[] buf = new byte[BUFFER_SIZE];
        while (!deflater.finished()) {
            int count = deflater.deflate(buf);
            bout.write(buf, 0, count);
        }
        deflater.end();
        bout.close();
        return bout.toByteArray();
    }
}

Related Tutorials