java 实现对字符串的压缩和解压

压缩字符串:
1. 创建字符串写入输出流os, 用于接收压缩后的byte[]
2. 用os 创建 GZIPOutputStream 对象gos
3. 将要压缩的字符串写入gos
4. 关闭gos
5. 从os中获取压缩后的内容

注意: 第4步和第5步顺序不能颠倒, 否则会抛出异常java.io.EOFException: Unexpected end of ZLIB input stream.

完整代码如下:
public static byte[] zip(String src) {
ByteArrayOutputStream os = null;
GZIPOutputStream gos = null;
byte[] dest = null;
try {
if (src == null) {
return dest;
}

os = new ByteArrayOutputStream();
gos = new GZIPOutputStream(os);

gos.write(src.getBytes("utf-8"));
IOUtils.closeQuietly(gos);
dest = os.toByteArray();
}catch (Exception e) {
throw new RuntimeException("Error zip string:" + src, e);
}finally {
IOUtils.closeQuietly(os);
}

return dest;
}

解压字符串:

大致过程和压缩差不多,就不啰嗦了.
注意要先关闭GZIPInputStream 再获取内容

public static String unzip(byte[] bytes) {
if (bytes == null) {
return null;
}

ByteArrayInputStream is = null;
ByteArrayOutputStream os = null;
GZIPInputStream gis = null;
String dest = null;
try {
is = new ByteArrayInputStream(bytes);
os = new ByteArrayOutputStream();
gis = new GZIPInputStream(is);
byte[] buffer = new byte[100];
for (int length = gis.read(buffer, 0, buffer.length); length > 0; length = gis.read(buffer)) {
os.write(buffer, 0, length);
}
IOUtils.closeQuietly(gis);
IOUtils.closeQuietly(is);
dest = os.toString("utf-8");

}catch (Exception e) {
throw new RuntimeException("Error unzip bytes:" + bytes, e);
}finally {

IOUtils.closeQuietly(os);
}

return dest;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用GZIP来实现超长字符串压缩解压。GZIP是一种数据压缩算法,它使用Lempel-Ziv算法和哈夫曼编码来进行数据压缩。以下是压缩解压的示例代码: 压缩: ```java public static String compress(String str) { if (str == null || str.length() == 0) { return str; } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toString("ISO-8859-1"); } catch (IOException e) { e.printStackTrace(); return null; } } ``` 解压: ```java public static String decompress(String compressed) { if (compressed == null || compressed.length() == 0) { return compressed; } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream( compressed.getBytes("ISO-8859-1")); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } // toString()使用平台默认编码,也可以显式指定如toString("UTF-8") return out.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } ``` 以上代码中,压缩函数将字符串转换为字节数组,然后使用GZIPOutputStream进行压缩,最后将压缩后的字节数组转换为字符串并返回。解压函数将压缩后的字符串转换为字节数组,然后使用GZIPInputStream进行解压,最后将解压后的字节数组转换为字符串并返回。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值