用Deflater与Inflater实现字节的压缩与解压

百度了一下,deflate就是zip压缩“ZIP,是一个计算机文件的压缩的算法,原名Deflate(真空)

 

package com.yangxiutian;

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

public class ZLibUtils {
	/**
	 * 用zip算法解压压缩字节
	 * @param zipByte 输入的压缩字节
	 * @return	解压好的解压字节
	 * @throws IOException
	 */
	public static byte[] decompress(byte[] zipByte) throws IOException {
		ByteArrayOutputStream aos=new ByteArrayOutputStream(); 
		Inflater inflater=new Inflater();
		inflater.setInput(zipByte); 
		byte[] buff=new byte[1024];
		int byteNum=0;
		while(!inflater.finished()){
			try {
				byteNum=inflater.inflate(buff);
				aos.write(buff,0,byteNum);
			} catch (DataFormatException e) {
				e.printStackTrace();
			}
		}
		return aos.toByteArray();
	}
	
	/**
	 * 用zip算法压缩字节
	 * @param zipByte 输入的待压缩字节
	 * @return	压缩就绪的字节
	 * @throws IOException
	 */
	public static byte[] compress(byte[] bytes) throws IOException {
		ByteArrayOutputStream aos=new ByteArrayOutputStream(); 
		Deflater inflater=new Deflater();
		inflater.setInput(bytes);
		inflater.finish();
		byte[] buff=new byte[1024];
		int byteNum=0;
		while(!inflater.finished()){
			byteNum=inflater.deflate(buff);
			aos.write(buff, 0, byteNum);
		}
		return aos.toByteArray();
	}

}

你可能感兴趣的:(压缩,zip,解压,字节)