Deflater、Inflater压缩解压示例

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();
	}
}

你可能感兴趣的:(Deflater、Inflater压缩解压示例)