java 压缩与解压

Deflater 是用于压缩数据包的,当数据包比较大的时候,采用压缩后的数据,可以减少带宽的占用,加多传送的
速度,Inflater则时对压缩后的数据包解压用的

import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ValidateSignUtil {

	public static byte[] compress(String str) {
		Deflater compresser = new Deflater();
		compresser.setInput(str.getBytes());
		compresser.finish();

		byte[] compressed = new byte[str.length() + 1];
		int compressedDataLength = compresser.deflate(compressed);

		byte[] encodestrig = new byte[compressedDataLength];
		System.arraycopy(compressed, 0, encodestrig, 0, compressedDataLength);
		return encodestrig;
	}

	public static String 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 new String(bos.toByteArray());
	}
}

 

 

 

你可能感兴趣的:(java)