1 package com.jf.utils;
2
3 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
11 /**
12 * GZIPUtils工具类
13 */
14 public class GZIPUtils {
15
16 private static final String GZIP_ENCODE_UTF_8 = "UTF-8";
17
18 @SuppressWarnings("unused")
19 private static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
20
21 /**
22 * 字符串压缩为GZIP字节数组
23 * @param str
24 * @return
25 */
26 public static byte[] compress(String str) {
27 return compress(str, GZIP_ENCODE_UTF_8);
28 }
29
30 /**
31 * 字符串压缩为GZIP字节数组
32 * @param str
33 * @param encoding
34 * @return
35 */
36 public static byte[] compress(String str, String encoding) {
37 if (str == null || str.length() == 0)
38 return null;
39 ByteArrayOutputStream out = new ByteArrayOutputStream();
40 GZIPOutputStream gzip;
41 try {
42 gzip = new GZIPOutputStream(out);
43 gzip.write(str.getBytes(encoding));
44 gzip.close();
45 } catch (IOException e) {
46 return null;
47 }
48 return out.toByteArray();
49 }
50
51 /**
52 * GZIP解压缩
53 * @param bytes
54 * @return
55 */
56 public static byte[] uncompress(byte[] bytes) {
57 if (bytes == null || bytes.length == 0)
58 return null;
59 ByteArrayOutputStream out = new ByteArrayOutputStream();
60 ByteArrayInputStream in = new ByteArrayInputStream(bytes);
61 try {
62 GZIPInputStream ungzip = new GZIPInputStream(in);
63 byte[] buffer = new byte[256];
64 int n;
65 while ((n = ungzip.read(buffer)) >= 0) {
66 out.write(buffer, 0, n);
67 }
68 } catch (IOException e) {
69 return null;
70 }
71 return out.toByteArray();
72 }
73
74 /**
75 * @param bytes
76 * @return
77 */
78 public static String uncompressToString(byte[] bytes) {
79 return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
80 }
81
82 /**
83 *
84 * @param bytes
85 * @param encoding
86 * @return
87 */
88 public static String uncompressToString(byte[] bytes, String encoding) {
89 if (bytes == null || bytes.length == 0)
90 return null;
91 ByteArrayOutputStream out = new ByteArrayOutputStream();
92 ByteArrayInputStream in = new ByteArrayInputStream(bytes);
93 try {
94 GZIPInputStream ungzip = new GZIPInputStream(in);
95 byte[] buffer = new byte[256];
96 int n;
97 while ((n = ungzip.read(buffer)) >= 0) {
98 out.write(buffer, 0, n);
99 }
100 return out.toString(encoding);
101 } catch (IOException e) {
102 return null;
103 }
104 }
105
106 public static void main(String[] args) {
107 String str = "xxxx";
108 System.out.println("原长度:" + str.length());
109 System.out.println("压缩后字符串长度:" + GZIPUtils.compress(str).toString().length());
110 System.out.println("压缩后字符串:" + GZIPUtils.compress(str).toString());
111 // System.out.println("解压缩后字符串:" + StringUtils.newStringUtf8(GZIPUtils.uncompress(GZIPUtils.compress(str))));
112 System.out.println("解压缩后字符串:" + GZIPUtils.uncompressToString(GZIPUtils.compress(str)));
113 }
114 }