在java中,gzip压缩用GZIPOutputStream类实现,gzip解压缩用GZIPInputStream类来实现,为什么要用到gzip来压缩与解压缩Json数据呢?这是因为在数据传输当中,数据越小,传输越快,所以在很多情况下,都会用到gzip来压缩json数据,本案例是一个gzip工具类。
新建一个GzipUtils.java工具类,里面是gzip压缩与解压缩的方法,如下。
package demo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
/**
* GZIP压缩
*
*/
public static byte[] gzipCompress(byte[] source) throws Exception {
if (source == null || source.length == 0) {
return source;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(bos);
gout.write(source);
gout.close();
bos.close();
return bos.toByteArray();
}
/**
* GZIP解压缩
*
*/
public static byte[] gzipUncompress(byte[] source) throws Exception {
if (source == null || source.length == 0) {
return null;
}
InputStream bais = new ByteArrayInputStream(source);
byte[] buffer = new byte[1024];
int n;
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gin = null;
try {
gin = new GZIPInputStream(bais);
while ((n = gin.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
out.close();
bais.close();
return out.toByteArray();
} finally
{
gin.close();
}
}
}使用GzipUtils工具类,来看看gzip的压缩率到底有多大,我觉得gzip压缩是最好的压缩形式之一。
public static void main(String[] args) throws Exception {
String queryString = "{ firstName:Bill测试 , lastName:Gates }{ firstName:Bill , lastName:Gates }{ firstName:Bill , lastName:Gates }
{ firstName:Bill , lastName:Gates }{ firstName:Bill , lastName:Gates }{ firstName:Bill , lastName:Gates }
{ firstName:Bill , lastName:Gates }{ firstName:Bill , lastName:Gates }";
for (int i = 0; i < 10; i++) {
queryString = queryString + queryString;
}
System.out.println("压缩前长度:"+queryString.length());
byte[] zip = GzipUtils.gzipCompress(queryString.getBytes());
System.out.println("压缩后长度:"+zip.length);
//通过gzip解压压缩后的数据
byte[] bys = GzipUtils.gzipUncompress(zip);
System.out.println(new String(bys,"UTF-8"));
}通过gzip压缩的json数据效果非常明显,当然了,非常小的数据千万别压缩,因为越压缩,反而越大。上面gzip压缩后的效果如下,非常明显:
压缩前长度:288768 压缩后长度:1579