方法如下:
有两种实现,一种利用原生Java API,另外使用Apache common---->IOUtils
//测试通过gz压缩->base64编码后字符串
String queryString = "I am still alive";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(bos);
GZIPOutputStream gout = new GZIPOutputStream(b64os);
gout.write(queryString.getBytes("UTF-8"));
gout.close();
b64os.close();
byte b1[] = bos.toByteArray();
System.out.println("Encode:" + new String(b1));
// String s1 = null;
InputStream bais = new ByteArrayInputStream(b1);
Base64InputStream b64io = new Base64InputStream(bais);
GZIPInputStream gin = new GZIPInputStream(b64io);
//toString 方法建议制定编码,否则采用系统默认编码,出现中文编码错误的问题
System.out.println(IOUtils.toString(gin,"UTF-8"));
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
// int numBytesRead = 0;
// byte [] tempBytes = new byte[6000];
// while ((numBytesRead = gin.read(tempBytes, 0, tempBytes.length)) != -1)
// {
// baos.write(tempBytes, 0, numBytesRead);
// }
//
// s1 = new String(baos.toByteArray());
// s1= baos.toString();
// System.out.println(s1);
利用IOUtils能完成更多操作,不必要封装多层IO