java 字符串压缩之Snappy

引入maven

1
2
3
4
5
<dependency>
<groupId>org.xerial.snappy</groupId>
<artifactId>snappy-java</artifactId>
<version>1.1.4</version>
</dependency>

将字符串压缩成byte数组

使用iso8859-1编码(具体编码可以视具体字符串而定)。

1
2
3
public static String compress(String info) throws IOException {
return Snappy.compress(info, "ISO-8859-1");
}

将byte数组解码成字符串

使用iso8859-1编码(具体编码可以视具体字符串而定)。

1
2
3
public static String uncompress(byte[] info) throws IOException {
return Snappy.uncompressString(info, "ISO-8859-1");
}

二进制转字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
public static String byteTohex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs;
}

字符串转二进制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static byte[] hexTobyte(String str) {
if (str == null) {
return null;
}
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1) {
return null;
}
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}

完整的SnappyUtil.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
import java.io.IOException;
import org.xerial.snappy.Snappy;

public class SnappyUtil {

public static String compress(String info) throws IOException {
return byteTohex(Snappy.compress(info, "ISO-8859-1"));
}

public static String uncompress(String info) throws IOException {
return Snappy.uncompressString(hexTobyte(info), "ISO-8859-1");
}

private static String byteTohex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs;
}

private static byte[] hexTobyte(String str) {
if (str == null) {
return null;
}
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1) {
return null;
}
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}
}