chenrui
2025-02-27 146edfb05602373ad5b36771e1ede1e395d8ab62
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
package com.ruoyi.common.utils;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
 
/**
 * 压缩解压工具类
 */
public class GZipUtil {
 
 
    /**
     * 压缩
     * @param str
     * @return
     */
    public static String compress(String str) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
 
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(str.getBytes("utf-8"));
            gzip.close();
 
            return new String(out.toByteArray(), "iso-8859-1");
        } catch (Exception e) {
            e.printStackTrace();
            return str;
        }
 
    }
 
    /**
     * 解压
     * @param str
     * @return
     */
    public static String uncompress(String str) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
 
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("iso-8859-1"))){
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
 
            return new String(out.toByteArray(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return str;
        }
 
    }
}