工作需要把String类型的数据压缩成包存进数据库(BLOB)类型;
/**
字符串进行压缩
*/
public byte[] compress(String str) throws Exception {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return out.toByteArray();
}
/**
压缩文件解析成字符串
*/
public String uncompress(byte[] data) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(data);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
gunzip.close();
return new String( out.toByteArray(), "UTF-8");
}