Commons Compress VS. SharpZipLib
最近工作需要把数据库里面的压缩字段解压出来,这些压缩字段采用的压缩方法是由 SharpZipLib 的类库进行压缩的,但是解压这段需要使用java代码来实现。可怜的SharpZiplib,竟然没有提供java版本。从SharpZipLib的一些资料来看,貌似是专门给C#用的。所谓一把钥匙开一把锁。没提供java版本的类库,很悬啊?不会要自己去看源代码,然后再写个java版本的解压算法吧。
看了下SharpZipLib 对应的解压方法,还蛮简单的。首先我尝试用Java JDK自带的解压方法(java.util.zip.*)去解压,它能解压大部分,大约有百分之二三十解不出来,然后我去搜各种解压的第三方类库,越是偏门的越找。最后试了一下Apache Commons下面的Compress包,竟然有想不到的意外:全部能解出来。
下面贴出代码:
1: import java.io.ByteArrayInputStream;
2: import java.io.ByteArrayOutputStream;
3: import java.io.InputStream;
4:
5: import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
6: import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
7:
8: /**
9: * This class uses the commons-compress library to uncompress the data from SharpZipLib.
10: *
11: */
12: public class CommonsZipUtil {
13:
14: /**
15: * Uncompress data for the InputStream which is the binary data container.
16: * @param is
17: * @return Uncompressed byte data.
18: */
19: public static byte[] uncompress(InputStream is) {
20: if (is == null) {
21: return null;
22: }
23: ZipArchiveInputStream zis = new ZipArchiveInputStream(is, "UTF8", true, false);
24: try {
25: ZipArchiveEntry entry = zis.getNextZipEntry();
26: if (entry == null || entry.getSize() == 0) {
27: return new byte[0];
28: }
29:
30: byte[] buff = new byte[1024];
31: ByteArrayOutputStream baos = new ByteArrayOutputStream();
32: int size = 0;
33: while ((size = zis.read(buff, 0, buff.length)) != -1) {
34: baos.write(buff, 0, size);
35: }
36:
37: return baos.toByteArray();
38: } catch (Exception e) {
39: throw new RuntimeException("Failed to unzip the data for " + e.getMessage(), e);
40: } finally {
41: try {
42: zis.close();
43: } catch(Exception e) {
44: e.printStackTrace();
45: }
46: }
47: }
48:
49: /**
50: * Uncompress data for the byte array which is compressed.
51: * @param zippedData
52: * @return
53: */
54: public static byte[] uncompress(byte[] zippedData) {
55: //System.out.println("ZZZ: input byte length= " + (zippedData == null ? 0 : zippedData.length));
56: if (zippedData == null) {
57: return null;
58: }
59: ByteArrayInputStream baos = new ByteArrayInputStream(zippedData);
60: return uncompress(baos);
61: }
62: }