数据压缩

本文介绍了一个用于字符串压缩和解压的帮助类CompressUtil的实现。该类利用GZIP算法进行压缩与解压缩操作,并支持设置编码方式。通过示例代码展示了如何使用此类对字符串进行压缩成字节数组及如何将压缩后的字节数组还原为原始字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.IOException;
 6 import java.util.zip.GZIPInputStream;
 7 import java.util.zip.GZIPOutputStream;
 8 
 9 /**
10  * <p>
11  * 功能描述:数据压缩帮助类
12  * </p>
13  */
14 public class CompressUtil {
15 
16     private static String encode = "utf-8";
17 
18     public String getEncode() {
19         return encode;
20     }
21 
22     public void setEncode(String encode) {
23         CompressUtil.encode = encode;
24     }
25 
26     /**
27      * 字符串的压缩
28      * @param str
29      * @return byte[]
30      * @throws IOException
31      */
32     public static byte[] compress(String str) throws IOException {
33         // 创建一个新的 byte 数组输出流
34         ByteArrayOutputStream out = new ByteArrayOutputStream();
35         // 使用默认缓冲区大小创建新的输出流
36         GZIPOutputStream gzip = new GZIPOutputStream(out);
37         // 将 b.length 个字节写入此输出流
38         gzip.write(str.getBytes(encode));
39         gzip.close();
40         return out.toByteArray();
41     }
42 
43     /**
44      * 字符串的解压
45      * @param str
46      * @return
47      * @throws IOException
48      */
49     public static String unCompress(byte[] a) throws IOException {
50         // 创建一个新的 byte 数组输出流
51         ByteArrayOutputStream out = new ByteArrayOutputStream();
52         // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
53         ByteArrayInputStream in = new ByteArrayInputStream(a);
54         // 使用默认缓冲区大小创建新的输入流
55         GZIPInputStream gzip = new GZIPInputStream(in);
56         byte[] buffer = new byte[256];
57         int n = 0;
58         // 将未压缩数据读入字节数组
59         while ((n = gzip.read(buffer)) >= 0) {
60             // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
61             out.write(buffer, 0, n);
62         }
63         return out.toString(encode);
64     }
65 }

 

转载于:https://www.cnblogs.com/mybatis/p/5892385.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值