91名师指路-头部
91名师指路

java字符串压缩和解压缩

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:工具类

package com.mszl.common.utils;

import com.alibaba.fastjson.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {


/**
* 功能:字符串压缩
* 网址: https://91mszl.com
* @Author: zxb
* @Date: 2022-11-01 17:06:27
*/
public static String compress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return null;
}
// 创建一个byte数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用默认缓冲区大小创建新的输出流
GZIPOutputStream gzip = new GZIPOutputStream(out);
// 将str转成byte字节写入此输出流
gzip.write(str.getBytes("UTF-8"));
gzip.close();
// 使用指定的charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("ISO-8859-1");
}

/**
* 功能:字符串的解压
* 网址: https://91mszl.com
* @Author: zxb
* @Date: 2022-11-01 17:08:45
*/
public static String unCompress(byte[] b) {
try {
if (null == b || b.length <= 0) {
return null;
}
// 创建一个数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个ByteArrayInputStream,使用buf作为其缓冲区数组
ByteArrayInputStream in;
in = new ByteArrayInputStream(b);

// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n = 0;
while ((n = gzip.read(buffer)) >= 0) { // 将未压缩数据读入字节数组
// 将指定byte数组中从偏移量off开始的len个字节写入此byte数组输出流
out.write(buffer, 0, n);
}
// 使用指定的charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}

return null;
}


public static void main(String[] args) throws IOException {
JSONObject json=new JSONObject();
json.put("name", "张三");

for(int i=0; i<1000; i++){
json.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());
}

// 压缩
String str=json.toString();
System.out.println("压缩前: " + str);

String res=compress(str);
System.out.println("压缩后: " +res);

// 解压缩
byte[] bytes = res.getBytes("ISO-8859-1");
String uni=unCompress(bytes);
System.out.println("解压后: " + uni);
}


}


二:测试效果

压缩前大小为 80kb


压缩后大小为 36kb


压缩前比压缩后节约了一半以上的空间,效果还是很感人的。






2022-11-01 17:15:07     阅读(326)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部