package com.fei;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class GZipUtil {
/**
* 压缩
* 注:压缩后得到的byte[]数组不可直接转为String,否则将无法解压
*/
public static byte[] gZip(String s) {
if (s == null || "".equals(s.trim()))
return null;
try {
byte[] b = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(s.getBytes());
gzip.finish();
gzip.close();
b = bos.toByteArray();
bos.close();
return b;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 解压
* @param data
* @return
*/
public static String unGZip(byte[] data) {
byte[] b = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
GZIPInputStream gzip = new GZIPInputStream(bis);
byte[] buf = new byte[1024];
int num = -1;
while ((num = gzip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
gzip.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(baos.toByteArray());
}
/**
* 用BASE64编码
*/
public static String base64Encoder(byte[] b) {
if (b == null)
return null;
return new BASE64Encoder().encode(b);
}
/**
* 用BASE64解码
*/
public static byte[] base64Decoder(String s) throws Exception {
if (s == null)
return null;
return new BASE64Decoder().decodeBuffer(s);
}
public static void main(String[] args) throws Exception {
String str = "我要这天再也遮不住我的眼,我要这地埋不了我的心,我要这满天神佛烟飞灰散,我也要芸芸众生明白我的意!";
System.out.println("压缩前:" + str);
System.out.println("压缩前字节长度:" + str.getBytes().length);
byte [] gByte = gZip(str);
System.out.println("压缩后字节长度:" + gByte.length);
String base64GStr = base64Encoder(gByte);
System.out.println("压缩加密:" + base64GStr);
System.out.println("压缩加密后字节长度:" + base64GStr.getBytes().length);
byte [] gStrGByte = base64Decoder(base64GStr);
String decompString = unGZip(gStrGByte);
System.out.println("解缩解密:" + decompString);
}
}
运行结果:
压缩前:我要这天再也遮不住我的眼,我要这地埋不了我的心,我要这满天神佛烟飞灰散,我也要芸芸众生明白我的意!
压缩前字节长度:98
压缩后字节长度:110
压缩加密:H4sIAAAAAAAAADt36dKqq4/OvLly89Kmq7c27b6+8NylrUcu3l685hxYZuuNQx837T54GiR64QhM
9NCvM29Oftz+4eKZ7Sd3Xzq5CCy+6dKqO/vv7L926+Svw983XAfpuPRo8UIAoJ4MXmIAAAA=
压缩加密后字节长度:150
解缩解密:我要这天再也遮不住我的眼,我要这地埋不了我的心,我要这满天神佛烟飞灰散,我也要芸芸众生明白我的意!