forked from He-John/showdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGZIPCompressedUtils.java
More file actions
99 lines (94 loc) · 3.27 KB
/
GZIPCompressedUtils.java
File metadata and controls
99 lines (94 loc) · 3.27 KB
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
package com.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* @Auther: xglc.mxn
* @Date: 2019/3/18 10:01
* @Description: 压缩工具
*/
public class GZIPCompressedUtils {
/**
* 使用gzip进行压缩
*/
public static String compress(String primStr) {
if (primStr == null || primStr.length() == 0) {
return primStr;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(primStr.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* 使用gzip进行解压缩
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try {
compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
try {
out.close();
} catch (IOException e) {
}
}
return decompressed;
}
public static void main(String[] args) {
String str =
"1888888888888888888888884444444444444444444444444444443333333333333333332222222222222222288888888888888884444444444444444444444444443333d888888888888888866666";
System.out.println("原字符串:" + str);
System.out.println("原长度:" + str.length());
String compress = GZIPCompressedUtils.compress(str);
System.out.println("压缩后字符串:" + compress);
System.out.println("压缩后字符串长度:" + compress.length());
String string = GZIPCompressedUtils.uncompress(compress);
System.out.println("解压缩后字符串:" + string);
System.out.println("解压缩后字符串:" + str);
}
}