package test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPUtil {
/**
* 压缩指定的字符串
* @param str
* @return
* @throws IOException
*/
public static String compressEncode(String str) throws IOException{
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* zip 压缩后
* @param data
* @return
* @throws IOException
*/
public static String toGzip(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(bos);
GZIPOutputStream gout = new GZIPOutputStream(b64os);
gout.write(data.getBytes("UTF-8"));
gout.close();
b64os.close();
byte b1[] = bos.toByteArray();
return new String(b1);
}
/**
* 对字节类型进行解压缩
* @param bytes
* @return
* @throws IOException
*/
public static String uncompressDecode(String str) throws IOException {
if (str == null || str.length() == 0) {
return null;
}
byte[] bytes=new sun.misc.BASE64Decoder().decodeBuffer(str);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
if(!isGZIP(in)){
return str;
}
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
ungzip.close();
return out.toString();
}
/**
* 判断是否为gzip文件
* @param in
* @return
* @throws IOException
*/
private static boolean isGZIP(InputStream in) throws IOException{
boolean mFlag=true;
// 取前两个字节
byte[] header = new byte[2];
in.read(header);
in.reset();
int b3=((header[1] & 0xff)<<8) |(header[0] & 0xff);
if(b3 != GZIPInputStream.GZIP_MAGIC){
mFlag=false;
};
return mFlag;
}
public static void main(String[] args) throws IOException {
String str="测试字符串通过gzip压缩到base64编码";
System.out.println("compressEncode压缩后字段"+compressEncode(str));
System.out.println("toGzip压缩后字段"+toGzip(str));
System.out.println("b.解压缩后字段"+uncompressDecode(compressEncode(str)));
}
}