java gzip 压缩解压工具类

因为觉得简单,本想抱着百度直接拿过来用的心态,结果发现网上的代码都转载自同一份,且埋了一个坑,你不仔细去梳理,很难发现。

mark下需要注意的两点:

1. 编码/解码,压缩/解压缩是成对出现的

    编码:   byte[] by= "xxx".getBytes("utf-8");

    解码:   String s=new String(by,"utf-8")

    下面的代码遵循逻辑如下:

     压缩方法:  先编码后压缩

     解压缩方法:   先解压缩后解码

     有童鞋想在压缩方法里返回String,结果直接new String("压缩后字符串",''utf-8),然后结果是打死都解压不出来原文。new String()是个解码的过程,压缩后得到字节数组不重新进行编码,解码有什么意义。

 2.如果要对压缩方法返回字符串可以将字节数组转为16进制字符串,但是压缩的意义就没有了,因为内容大小基本没变


直接上代码:

package com.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {

	public static byte[] compress(String str)  {
		ByteArrayOutputStream out =null;
		GZIPOutputStream gzip=null;
		try{
			if (str == null || str.length() == 0) {
				return null;
			}
			out = new ByteArrayOutputStream();
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes("utf-8"));
			gzip.finish();
			return out.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			try{
				if(out!=null){
					out.close();
				}
				if(gzip!=null){
					gzip.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	public static String unCompress(byte []by) {
		ByteArrayOutputStream out=null;
		GZIPInputStream gunzip=null;
		try{
			if(by==null || by.length==0){
				return "";
			}
			out=new ByteArrayOutputStream();
			gunzip= new GZIPInputStream(new ByteArrayInputStream(by));
			byte[] buffer = new byte[1024];
			int n;
			while ((n=gunzip.read(buffer))!=-1) {
				out.write(buffer, 0, n);
			}
			out.flush();
			return new String(out.toByteArray(),"utf-8");
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}finally{
			try{
				if(out!=null){
					out.close();
				}
				if(gunzip!=null){
					gunzip.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		
		String str = "806715668,1091464537,1061006120,1142513520";
		
		System.out.println(str.getBytes("utf-8").length);
		System.out.println(compress(str).length);
		System.out.println(unCompress(compress(str)));
		
	}

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值