GZip 压缩字符串Java实践

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.bqteam.aurthur;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class StringGZip {
public static void main(String[] args) throws Exception {
StringBuilder value = new StringBuilder() ;
for (int i = 0; i < 1000; i++) {
value.append("BQteam String Java 压缩测试");
}
//字符串压缩为byte数组
byte[] values = value.toString().getBytes() ;
System.out.println("解压前大小"+values.length);
values = compress(values) ;
System.out.println("解压后大小"+values.length);
//把压缩后的byte数组转为字符串
String str = new String(values,"iso8859-1") ;

//做一些数据操作(演示输出)
System.out.println(str);

//将接受到的字符串转换为byte数组
values = str.getBytes("iso8859-1") ;

//解压缩这个byte数组
values = decompress(values) ;
System.out.println(new String(values, "utf-8"));

}

/**
* 数据解压缩
*
* @param data
* @return
* @throws Exception
*/

public static byte[] decompress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

// 解压缩
decompress(bais, baos);
data = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return data;
}

/**
* 数据解压缩
*
* @param is
* @param os
* @throws Exception
*/

public static void decompress(InputStream is, OutputStream os)
throws Exception {


GZIPInputStream gis = new GZIPInputStream(is);

int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}

gis.close();
}

public static byte[] compress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

// 压缩
compress(bais, baos);
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
static final int BUFFER = 10240 ;

/**
* 数据压缩
*
* @param is
* @param os
* @throws Exception
*/

public static void compress(InputStream is, OutputStream os)
throws Exception {


GZIPOutputStream gos = new GZIPOutputStream(os);

int count;
byte data[] = new byte[BUFFER];
while ((count = is.read(data, 0, BUFFER)) != -1) {
gos.write(data, 0, count);
}
gos.finish();
gos.flush();
gos.close();
}

}