Я создал класс-оболочку JZIP для моего проекта UFM (Universal File Mover) с открытым исходным кодом Java. Вы можете скачать исходный код с здесь .
Вот только класс JZip. У него есть 2 метода: compressData и depressData. Оба ожидают байт [] для ввода и дают байт [] в качестве вывода. Это супер просто в использовании.
package com.capitalware.ufm.handlers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import com.capitalware.ufm.UFM;
/**
* This class will handle all of UFM's compression and decompression work.
* @author Roger Lacroix
* @version 1.0
* @license Apache 2 License
*/
public class JZip
{
/**
* The constructor - make sure nothing instantiates this class.
* It must be accessed in a static way.
*/
private JZip()
{}
/**
* This method will compress a byte array of data.
*
* @param inputData an array of bytes
* @return byte array of the contents of the file.
*/
public static byte[] compressData(byte[] inputData)
{
// Create the compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
// Give the compressor the data to compress
compressor.setInput(inputData);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(inputData.length);
// Compress the data
byte[] buf = new byte[65536];
while (!compressor.finished())
{
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try
{
bos.close();
}
catch (IOException e)
{
UFM.logger.fatal("IOException: " + e.getLocalizedMessage());
}
// return compressed data
return bos.toByteArray();
}
/**
* This method will decompress a byte array of compressed data.
*
* @param compressedData an array of bytes
* @return byte array of uncompressed data
*/
public static byte[] decompressData(byte[] compressedData)
{
// Create the decompressor and give it the data to compress
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
// Decompress the data
byte[] buf = new byte[65536];
while (!decompressor.finished())
{
try
{
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
catch (DataFormatException e)
{
UFM.logger.fatal("DataFormatException: " + e.getLocalizedMessage());
}
}
try
{
bos.close();
}
catch (IOException e)
{
UFM.logger.fatal("IOException: " + e.getLocalizedMessage());
}
// return uncompressed data
return bos.toByteArray();
}
}