Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active October 14, 2015 13:42
Show Gist options
  • Save Crydust/3e8d279c82d5cca26227 to your computer and use it in GitHub Desktop.
Save Crydust/3e8d279c82d5cca26227 to your computer and use it in GitHub Desktop.
java deflate compress and decompress
public class DeflateUtil {
public static byte[] compressBytes(final byte[] input) {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final byte[] buf = new byte[1024];
final Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION);
compresser.setInput(input);
compresser.finish();
while (!compresser.finished()) {
final int compressedDataLength = compresser.deflate(buf);
bos.write(buf, 0, compressedDataLength);
}
compresser.end();
return bos.toByteArray();
}
public static byte[] decompressBytes(final byte[] input) throws DataFormatException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final byte[] buf = new byte[1024];
final Inflater decompresser = new Inflater();
decompresser.setInput(input, 0, input.length);
while (!decompresser.finished()) {
final int resultLength = decompresser.inflate(buf);
bos.write(buf, 0, resultLength);
}
decompresser.end();
return bos.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment