本文介绍在Android中使用GZIPOutputStream进行压缩的方法,通过测试,在c#中用GZipStream可解压缩本方法压缩后的数据。参数 normalString 为压缩前的字符串,输出为 Base64 编码的字符串。
public String Compress(String normalString) throws IOException{
byte[] t = normalString.getBytes("UTF-8");
byte[] result;
ByteArrayInputStream in = new ByteArrayInputStream(t);
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
try{
byte[] buffer = new byte[4096];
int n = 0;
while((n = in.read(buffer, 0, buffer.length)) > 0){
gzip.write(buffer, 0, n);
}
}finally{
gzip.close();
}
in.close();
out.close();
result = out.toByteArray();
return Base64.encodeToString(result, Base64.DEFAULT);
}