Wednesday, November 04, 2009

Compressing a Byte Array

This Java tip illustrates an example of compressing a Byte Array. Developer may compress a byte array with the help of Deflater class.
byte[] input = "compression string".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try {
bos.close();
} catch (IOException e) {
}
byte[] compressedData = bos.toByteArray();

java-tips.org

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory