首页
›
java › java.util.zip.Deflater 压缩 inflater解压
java.util.zip.Deflater 压缩 inflater解压
lidasheng
2015年3月23日
java
- import java.util.zip.Deflater;
- import java.util.zip.Inflater;
- import java.util.zip.DataFormatException;
- import java.io.ByteArrayOutputStream;
- public class CompressionTools {
-
- private CompressionTools() {}
- public static byte[] compress(byte[] value, int offset, int length, int compressionLevel) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
- Deflater compressor = new Deflater();
- try {
- compressor.setLevel(compressionLevel);
- compressor.setInput(value, offset, length);
- compressor.finish();
-
- final byte[] buf = new byte[1024];
- while (!compressor.finished()) {
-
- int count = compressor.deflate(buf);
-
- bos.write(buf, 0, count);
- }
- } finally {
- compressor.end();
- }
- return bos.toByteArray();
- }
- public static byte[] compress(byte[] value, int offset, int length) {
- return compress(value, offset, length, Deflater.BEST_COMPRESSION);
-
- }
- public static byte[] compress(byte[] value) {
- return compress(value, 0, value.length, Deflater.BEST_COMPRESSION);
- }
- public static byte[] decompress(byte[] value) throws DataFormatException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
- Inflater decompressor = new Inflater();
- try {
- decompressor.setInput(value);
- final byte[] buf = new byte[1024];
- while (!decompressor.finished()) {
- int count = decompressor.inflate(buf);
- bos.write(buf, 0, count);
- }
- } finally {
- decompressor.end();
- }
- return bos.toByteArray();
- }
- }
发表评论