Deflater、Inflater压缩解压示例

来源:互联网 发布:微星没有淘宝旗舰店 编辑:程序博客网 时间:2024/06/05 19:34
package com.yt.lq.utils;import java.util.zip.Deflater;import java.util.zip.Inflater;import java.util.zip.DataFormatException;import java.io.ByteArrayOutputStream;public class CompressionTool {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();}}

原创粉丝点击