用zip压缩json串 压缩率很高很高 测试200K 压缩后4k 发送到前端需要解压缩 算法gzip的算法是一样的
package author.zhaolei.gzip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIP {
/**
* 压缩
*/
public void compress() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("d:/test.txt"), "UTF-8"));
BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("d:/test.xx")));
int c;
while ((c = in.read()) != -1) {
out.write(String.valueOf((char) c).getBytes("UTF-8"));
}
in.close();
out.close();
}
/**
* 测试用的
*/
public void copy4check() throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("d:/test.xx"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:/test.xxx"));
int c;
while((c=in.read())!=-1){
out.write(c);
}
out.close();
in.close();
}
/**
* 解压缩
*/
public void unCompress() throws IOException {
BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("d:/test.xx")),"UTF-8"));
String s;
while ((s = in2.readLine()) != null) {
System.out.println(s);
}
in2.close();
}
public static void main(String[] args) throws IOException {
GZIP c = new GZIP();
c.compress();
c.copy4check();
c.unCompress();
}
}