Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;

import java.util.zip.Deflater;

public class Main {
    public static byte[] compress(ByteBuffer byteBuf) {
        return compress(getByteArrayFromBuffer(byteBuf));
    }

    public static byte[] compress(byte[] data) {
        Deflater deflater = new Deflater();
        deflater.setInput(data);
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);

            deflater.finish();
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int count = deflater.deflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            deflater.end();
        }

    }

    private static byte[] getByteArrayFromBuffer(ByteBuffer byteBuf) {
        byteBuf.flip();
        byte[] row = new byte[byteBuf.limit()];
        byteBuf.get(row);
        byteBuf.clear();
        return row;
    }
}