字符串压缩
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import sun.misc.BASE64Decoder; public class StringCompression { public static final byte [] compress(String str) { if (str == null ) return null ; byte [] compressed; ByteArrayOutputStream out = null ; ZipOutputStream zout = null ; try { out = new ByteArrayOutputStream(); zout = new ZipOutputStream(out); zout.putNextEntry( new ZipEntry( "0" )); zout.write(str.getBytes()); zout.closeEntry(); compressed = out.toByteArray(); } catch (IOException e) { compressed = null ; } finally { if (zout != null ) { try { zout.close(); } catch (IOException e) { } } if (out != null ) { try { out.close(); } catch (IOException e) { } } } return compressed; } /** * 将压缩后的 byte[] 数据解压缩 * * @param compressed * 压缩后的 byte[] 数据 * @return 解压后的字符串 */ public static final String decompress( byte [] compressed) { if (compressed == null ) return null ; ByteArrayOutputStream out = null ; ByteArrayInputStream in = null ; ZipInputStream zin = null ; String decompressed; try { out = new ByteArrayOutputStream(); in = new ByteArrayInputStream(compressed); zin = new ZipInputStream(in); ZipEntry entry = zin.getNextEntry(); byte [] buffer = new byte [ 1024 ]; int offset = - 1 ; while ((offset = zin.read(buffer)) != - 1 ) { out.write(buffer, 0 , offset); } decompressed = out.toString(); } catch (IOException e) { decompressed = null ; } finally { if (zin != null ) { try { zin.close(); } catch (IOException e) { } } if (in != null ) { try { in.close(); } catch (IOException e) { } } if (out != null ) { try { out.close(); } catch (IOException e) { } } } return decompressed; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· 软件产品开发中常见的10个问题及处理方法
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?
· 《HelloGitHub》第 108 期