jiangping
2023-10-24 c6d20c6e1db82b204cf59e058bc3ba2a9cd84a1e
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
package com.doumee.core.utils;
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
 
import org.apache.commons.io.output.ByteArrayOutputStream;
 
public class CompressUtil {
    /**
     * 对字节数组进行gzip压缩
     * <p>
     * 
     * @author jgzhang2, 2014-8-13
     * 
     *            :压缩前的字节数组
     * @return:压缩后的字节数组
     */
    public static byte[] compressByGzip(byte[] str) {
        if (str == null || str.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str);
            gzip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
 
    /**
     * <p>
     * 
     * @author jgzhang2, 2014-8-16
     * 
     * @param bytesToUncompress
     * @param encoding
     * @return
     * @throws IOException
     */
    public static byte[] uncompressByGzip(byte[] bytesToUncompress,
            String encoding) throws IOException {
        if (bytesToUncompress == null || bytesToUncompress.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytesToUncompress);
 
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
 
        return out.toByteArray();
 
    }
}