Sun 自带的Gzip压缩解压xml实例
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class TestXml {
/**
* 压缩
*/
public static String zipXml(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
BASE64Encoder base64encoder = new BASE64Encoder();
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return base64encoder.encode(out.toByteArray());
}
/**
* 解压
*/
public static String unZipXml(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
BASE64Decoder base64decoder = new BASE64Decoder();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bytes = base64decoder.decodeBuffer(str);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString("UTF-8");
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
File file = new File("E:hz.xml");
is = (InputStream)new FileInputStream(new File("E:hz.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Byte[] bt = null;
//BufferedInputStream input = new BufferedInputStream(is);// 输入流,用于接收请求的数据
//ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(2048);// 请求数据存放对象,使用了参数2048
//
//byte[] bufferRead = new byte[1024];// 数据缓冲区
//int count = 0;// 每个缓冲区的实际数据长度
//
//while ((count = input.read(bufferRead)) != -1) {
//byteOutput.write(bufferRead, 0, count);
//}
List ioList = IOUtils.readLines(is);
StringBuilder sb = new StringBuilder(1024);
for(int i =0; i < ioList.size() ; i++){
sb.append(ioList.get(i));
}
String inStr = sb.toString();
System.out.println("原长度:" + inStr.length());
String outStr = zipXml(inStr);
System.out.println("长度:" + outStr.length());
System.out.println((double)inStr.length()/outStr.length());
System.out.println("压缩比:" + (double)(int)(((double)inStr.length()/outStr.length() + 0.005) * 100) / 100 + " : 1");
System.out.println("压缩后内容:" + outStr);
//String unStr = unZipXml(outStr);
//System.out.println("长度:" + unStr.length());
//System.out.println("解压后内容:" + unStr);
}
}