工具类:
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Gzip压缩
* 字符串长度太小,压缩不明显
* @author XXX
*/
public class GzipUtil {
/**
* 压缩
*
* @param strData 原字符串
* @return 压缩后字符串
* @throws Exception
*/
public static String gzip(String strData) throws Exception {
if (strData == null || strData.length() == 0) {
return strData;
}
byte[] data = strData.getBytes("UTF-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
gzip.close();
byte[] ret = bos.toByteArray();
bos.close();
return Base64.encodeBase64String(ret);
}
/**
* 解压缩
*
* @param base64Str 压缩后字符串
* @return 源字符串
* @throws Exception
*/
public static String unGzip(String base64Str) throws IOException {
if (base64Str == null || base64Str.length() == 0) {
return base64Str;
}
byte[] data = Base64.decodeBase64(base64Str);
ByteArrayInputStream in = new ByteArrayInputStream(data);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int num;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((num = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, num);
}
gunzip.close();
in.close();
byte[] ret = out.toByteArray();
out.flush();
out.close();
return new String(ret, "UTF-8");
}
/**
* 读取文件流
*
* @param fileName 文件名
* @return 字符串
*/
public static String readToString(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return null;
}
}
}
使用压缩:
解压缩: