Java ByteBuffer Compress compress(ByteBuffer byteBuf)

Here you can find the source of compress(ByteBuffer byteBuf)

Description

compress

License

Open Source License

Declaration

public static byte[] compress(ByteBuffer byteBuf) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;

import java.nio.ByteBuffer;

import java.util.zip.Deflater;

public class Main {
    public static byte[] compress(ByteBuffer byteBuf) {
        return compress(getByteArrayFromBuffer(byteBuf));
    }/*  w w  w .  j  a va  2  s.c om*/

    public static byte[] compress(byte[] data) {

        byte[] output = null;

        Deflater compresser = new Deflater();
        compresser.setInput(data);
        compresser.finish();

        ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
        byte[] result = new byte[1024];
        try {
            while (!compresser.finished()) {
                int length = compresser.deflate(result);
                out.write(result, 0, length);
            }
            output = out.toByteArray();
        } finally {
            try {
                out.close();
            } catch (Exception e) {
            }
            compresser.end();
        }

        return output;
    }

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

Related

  1. compress(ByteBuffer buffer)
  2. decompress(ByteBuffer buffer)