ZIP压缩和解压字符串
2024-08-31 02:50:37
由于ZIP压缩会产生头信息, 所以当字符串长度没有达到一定规模的时候, 压缩后的长度可能比原来的还长
// 将一个字符串按照zip方式压缩和解压缩
public class ZipUtil { // 压缩
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
} // 解压缩
public static String uncompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(str.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("GBK")
return out.toString();
} // 测试方法
public static void main(String[] args) throws IOException { //测试字符串
String str="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221"; System.out.println("原长度:"+str.length()); System.out.println("压缩后:"+ZipUtil.compress(str).length()); System.out.println("解压缩:"+ZipUtil.uncompress(ZipUtil.compress(str)));
}
}
最新文章
- Nodejs基础中间件Connect
- Windows service无法删除怎么办?
- 写给自己看的Linux运维基础(四) - python环境
- 织梦dedecms简略标题调用标签用法指南
- DevExpress GridControl 使用方法技巧 总结 收录整理
- 【JavaScript】重温Javascript继承机制
- MSSQLSERVER数据库- SQL删除重复数据的五种方式
- VC++添加工具栏
- C# Socket学习笔记一
- java学习之tcp与udp的实现
- ABP入门系列(14)——应用BootstrapTable表格插件
- openstack Q版部署-----nova服务配置-控制节点(5)
- 线程的中断(Lock与synchronized)
- 在 xilinx SDK 使用 math.h
- tomcat的缺少tcnative-1.dll的解决(申明:来源于网络)
- iqueryable lambda表达式
- forget word out a~2
- UI5-文档-4.12-Shell Control as Container
- [转]你真的了解 console 吗
- 洛谷.4252.[NOI2006]聪明的导游(提答 直径 随机化)