ZIP压缩和解压字符串

由于ZIP压缩会产生头信息, 所以当字符串长度没有达到一定规模的时候, 压缩后的长度可能比原来的还长

 1 // 将一个字符串按照zip方式压缩和解压缩
 2 public class ZipUtil {
 3 
 4     // 压缩
 5     public static String compress(String str) throws IOException {
 6         if (str == null || str.length() == 0) {
 7             return str;
 8         }
 9         ByteArrayOutputStream out = new ByteArrayOutputStream();
10         GZIPOutputStream gzip = new GZIPOutputStream(out);
11         gzip.write(str.getBytes());
12         gzip.close();
13         return out.toString("ISO-8859-1");
14     }
15 
16     // 解压缩
17     public static String uncompress(String str) throws IOException {
18         if (str == null || str.length() == 0) {
19             return str;
20         }
21         ByteArrayOutputStream out = new ByteArrayOutputStream();
22         ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
23         GZIPInputStream gunzip = new GZIPInputStream(in);
24         byte[] buffer = new byte[256];
25         int n;
26         while ((n = gunzip.read(buffer)) >= 0) {
27             out.write(buffer, 0, n);
28         }
29         // toString()使用平台默认编码,也可以显式的指定如toString("GBK")
30         return out.toString();
31     }
32 
33     // 测试方法
34     public static void main(String[] args) throws IOException {
35 
36         //测试字符串
37         String str="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221";
38 
39         System.out.println("原长度:"+str.length());
40 
41         System.out.println("压缩后:"+ZipUtil.compress(str).length());
42 
43         System.out.println("解压缩:"+ZipUtil.uncompress(ZipUtil.compress(str)));
44     }
45 }
原文地址:https://www.cnblogs.com/ultrazb/p/3758646.html