Last active
October 14, 2015 13:42
-
-
Save Crydust/3e8d279c82d5cca26227 to your computer and use it in GitHub Desktop.
java deflate compress and decompress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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