So many of you not aware how to use java.util.zip package to compress and uncompress the data. So here are some utility methods for your understanding
public static byte [] zip (byte[] uncompressedData, int off, int len)
{
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(uncompressedData, off, len);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(len);
byte[] buf = new byte[1024];
while (!compressor.finished())
{
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try
{
bos.close();
}
catch (IOException e)
{
}
return bos.toByteArray();
}
public static byte [] unzip (byte [] compressedData, int off, int len)
{
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData, off, len);
ByteArrayOutputStream bos = null;
bos = new ByteArrayOutputStream(len);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished())
{
try
{
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
catch (DataFormatException e)
{
}
}
try
{
bos.close();
}
catch (IOException e)
{
}
return bos.toByteArray();
}
No comments:
Post a Comment