最新需要提供一个文本数据交换的接口,由于数据量比较大,需要对数据进行压缩传输,节省流量,所以写了一个使用Gzip进行数据压缩的小公举。
代码:
public class GzipUtil {
/**
* 压缩数据
* @param bytes
* @return
* @throws IOException
*/
public static byte[] compress(byte[] bytes) throws IOException{
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out)){
gzip.write(bytes);
gzip.close();
return out.toByteArray();
}
}
/**
* gzip压缩字符串
* @param content
* @param charset
* @return
* @throws IOException
*/
public static byte[] compress(String content, String charset) throws IOException {
Assert.notNull(content, "null content error");
return compress(content.getBytes(charset));
}
/**
* gizp解压
* @param in
* @return
* @throws IOException
*/
public static byte[] uncompress(InputStream in) throws IOException {
try(ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gin = new GZIPInputStream(in)){
byte[] buffer = new byte[1024];
int len;
while ((len = gin.read(buffer)) >= 0){
out.write(buffer, 0 ,len);
}
return out.toByteArray();
}
}
/**
* 解压缩为字符串
* @param in
* @param charset
* @return
* @throws IOException
*/
public static String uncompress(InputStream in, String charset) throws IOException {
byte[] bytes = uncompress(in);
return new String(bytes, charset);
}
}
工具测试:
@Test
public void test(){
try {
byte[] xiyouji = Files.readAllBytes(Paths.get("西游记.txt"));
System.out.println("压缩前体积:" + xiyouji.length/1024 + "k");
byte[] compress = GzipUtil.compress(xiyouji);
System.out.println("压缩后体积:" + compress.length/1024 + "k");
byte[] uncompress = GzipUtil.uncompress(new ByteArrayInputStream(compress));
System.out.println("解压后体积:" + uncompress.length/1024 + "k");
} catch (IOException e) {
e.printStackTrace();
}
}
测试结果:
压缩前体积:2102k
压缩后体积:935k
解压后体积:2102k