packagecom.rick.utils;import java.io.*;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;/********************************************************
*@Desc: gizp工具类
*@Author: ZRP
*@Date: 2017/11/9 9:31
********************************************************/
public classGzipUtil {/*** @Desc : gzip压缩
* @Author : ZRP
* @Params: [data]
* @Return: byte[]
* @Date : 2017/11/9 9:43*/
public static byte[] gzip(byte[] data) throwsException {
ByteArrayOutputStream bos= newByteArrayOutputStream();
GZIPOutputStream gzip= newGZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
gzip.close();byte[] ret =bos.toByteArray();
bos.close();returnret;
}/*** @Desc : gzip解压缩
* @Author : ZRP
* @Params: [data]
* @Return: byte[]
* @Date : 2017/11/9 9:47*/
public static byte[] ungzip(byte[] data) throwsException{
ByteArrayInputStream bis= newByteArrayInputStream(data);
GZIPInputStream gzip= newGZIPInputStream(bis);byte[] buf = new byte[1024];int num = -1;
ByteArrayOutputStream bos= newByteArrayOutputStream();while ((num = gzip.read(buf, 0, buf.length)) != -1){
bos.write(buf,0, num);
}
gzip.close();
bis.close();byte[] ret =bos.toByteArray();
bos.flush();
bos.close();returnret;
}/*** 测试压缩和还原
*@paramargs
*@throwsException*/
public static void main(String[] args) throwsException{//读取文件
String readPath = System.getProperty("user.dir") + File.separatorChar + "sources" + File.separatorChar + "001.jpg";
File file= newFile(readPath);
FileInputStream in= newFileInputStream(file);byte[] data = new byte[in.available()];
in.read(data);
in.close();
System.out.println("文件原始大小:" +data.length);//测试压缩
byte[] ret1 =GzipUtil.gzip(data);
System.out.println("压缩之后大小:" +ret1.length);byte[] ret2 =GzipUtil.ungzip(ret1);
System.out.println("还原之后大小:" +ret2.length);//写出文件
String writePath = System.getProperty("user.dir") + File.separatorChar + "receive" + File.separatorChar + "001.jpg";
FileOutputStream fos= newFileOutputStream(writePath);
fos.write(ret2);
fos.close();
}
}