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