Java字符串压缩存储

  1. import java.io.ByteArrayInputStream;    
  2. import java.io.ByteArrayOutputStream;    
  3. import java.io.IOException;    
  4. import java.util.zip.GZIPInputStream;    
  5. import java.util.zip.GZIPOutputStream;    
  6.     
  7. public class StringCompression {    
  8.   
  9.     static String  code="UTF-8";    
  10.     public static String compress(String str) throws IOException {    
  11.         System.out.println("压缩之前的字符串大小:"+str.length());    
  12.         if (str == null || str.length() == 0) {    
  13.             return str;    
  14.         }    
  15.         ByteArrayOutputStream out = new ByteArrayOutputStream();    
  16.         GZIPOutputStream gzip = new GZIPOutputStream(out);    
  17.         gzip.write(str.getBytes());    
  18.         gzip.close();    
  19.         return out.toString("ISO-8859-1");    
  20.     }    
  21.     
  22.     public static String uncompress(String str) throws IOException {    
  23.         System.out.println("压缩之后的字符串大小:"+str.length());    
  24.         if (str == null || str.length() == 0) {    
  25.             return str;    
  26.         }    
  27.         ByteArrayOutputStream out = new ByteArrayOutputStream();    
  28.         ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));    
  29.         GZIPInputStream gunzip = new GZIPInputStream(in);    
  30.         byte[] buffer = new byte[256];    
  31.         int n;    
  32.         while ((n = gunzip.read(buffer)) >= 0) {    
  33.             out.write(buffer, 0, n);    
  34.         }    
  35.         return out.toString();    
  36.     }    
  37.     
  38.     public static void main(String[] args) throws IOException {    
  39.             
  40.         System.out.println(StringCompression.compress("fdsagagdsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"));  
  41.         System.out.println(StringCompression.uncompress(StringCompression.compress("fsafgdfdsgfdgfdghfhgfhgfhdgdsfagdsgdasgddddddddddddddddddddddddd")));  
  42.     }  
  43. }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值