package cn.shinkong.cxf.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.util.Base64;
public class Gzip_date {
/** 字符串压缩为字节数组
* @param String 源数据
* @return String 压缩后的数据
*/
public static String compressToByte(String str){
if (str == null || str.length() == 0) {
return null;
}
//实现了一个输出流,其中的数据被写入一个 byte 数组。
ByteArrayOutputStream out = new ByteArrayOutputStream();
//GZIP 文件格式写入压缩数据实现流过滤器
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
//将字节数组写入压缩输出流。
gzip.write(str.getBytes("utf-8"));
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
//BASE64转码
return Base64.encode(out.toByteArray());
}
/*
* 字节数组解压缩后返回字符串
*/
public static String uncompressToString(String str) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
try {
in = new ByteArrayInputStream(Base64.decode((str)));
} catch (WSSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
//gunzip.read(buffer) 将未压缩数据读入字节数组。
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString("utf-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 将字节数组转换成16进制字符串
*
* @param buf
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}