数据压缩

import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.IOException;
 6 import java.util.zip.GZIPInputStream;
 7 import java.util.zip.GZIPOutputStream;
 8 
 9 /**
10  * <p>
11  * 功能描述:数据压缩帮助类
12  * </p>
13  */
14 public class CompressUtil {
15 
16     private static String encode = "utf-8";
17 
18     public String getEncode() {
19         return encode;
20     }
21 
22     public void setEncode(String encode) {
23         CompressUtil.encode = encode;
24     }
25 
26     /**
27      * 字符串的压缩
28      * @param str
29      * @return byte[]
30      * @throws IOException
31      */
32     public static byte[] compress(String str) throws IOException {
33         // 创建一个新的 byte 数组输出流
34         ByteArrayOutputStream out = new ByteArrayOutputStream();
35         // 使用默认缓冲区大小创建新的输出流
36         GZIPOutputStream gzip = new GZIPOutputStream(out);
37         // 将 b.length 个字节写入此输出流
38         gzip.write(str.getBytes(encode));
39         gzip.close();
40         return out.toByteArray();
41     }
42 
43     /**
44      * 字符串的解压
45      * @param str
46      * @return
47      * @throws IOException
48      */
49     public static String unCompress(byte[] a) throws IOException {
50         // 创建一个新的 byte 数组输出流
51         ByteArrayOutputStream out = new ByteArrayOutputStream();
52         // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
53         ByteArrayInputStream in = new ByteArrayInputStream(a);
54         // 使用默认缓冲区大小创建新的输入流
55         GZIPInputStream gzip = new GZIPInputStream(in);
56         byte[] buffer = new byte[256];
57         int n = 0;
58         // 将未压缩数据读入字节数组
59         while ((n = gzip.read(buffer)) >= 0) {
60             // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
61             out.write(buffer, 0, n);
62         }
63         return out.toString(encode);
64     }
65 }

 

posted @ 2016-09-21 13:54  SpringMVCMaven  阅读(1143)  评论(0编辑  收藏  举报