Java中字符串压缩的操作


这段时间项目中碰到一个问题,就是在做页面操作的时候,要保存的数据长度大于了表定义的字段长度,我们现在的项目是基于component开发,由于component是属于德国人开发,且德国人不愿意更改他们的设计,所以最后没有办法最后只能想到了一个对字符串进行压缩然后把压缩后的字符串存进数据库中,当需要从数据库中取数据时,需要对取出的数据进行解压缩,以前没有碰到过这种情况,所以花了很久的时间才写好了一个对字符串进行压缩和解压缩的类,如果写的不恰当的地方或者有更好的办法,还希望各位不吝赐教,该类的代码如下:

 
  1. package com.eric.io;  
  2. import java.io.ByteArrayInputStream;  
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.zip.GZIPInputStream;  
  6. import java.util.zip.GZIPOutputStream;  
  7.   
  8. public class StringCompression {  
  9. //经过实践考证,当需要压缩的字符串长度越大时,压缩的效果越明显   
  10.     static String  code="UTF-8";  
  11.     public static String compress(String str) throws IOException {  
  12.         System.out.println("压缩之前的字符串大小:"+str.length());  
  13.         if (str == null || str.length() == 0) {  
  14.             return str;  
  15.         }  
  16.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  17.         GZIPOutputStream gzip = new GZIPOutputStream(out);  
  18.         gzip.write(str.getBytes());  
  19.         gzip.close();  
  20.         return out.toString("ISO-8859-1");  
  21.     }  
  22.   
  23.     public static String uncompress(String str) throws IOException {  
  24.         System.out.println("压缩之后的字符串大小:"+str.length());  
  25.         if (str == null || str.length() == 0) {  
  26.             return str;  
  27.         }  
  28.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  29.         ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));  
  30.         GZIPInputStream gunzip = new GZIPInputStream(in);  
  31.         byte[] buffer = new byte[256];  
  32.         int n;  
  33.         while ((n = gunzip.read(buffer)) >= 0) {  
  34.             out.write(buffer, 0, n);  
  35.         }  
  36.         return out.toString();  
  37.     }  
  38.   
  39.     public static void main(String[] args) throws IOException {  
  40.           
  41.         System.out.println(StringCompression.uncompress(StringCompression.compress(OracleCompressTest.append("i come from china"))));  
  42.     }  
  43.   
  44. }  
  45.   
  46. /* 
  47.  *  
  48.  * History: 
  49.  *  
  50.  *  
  51.  *  
  52.  * $Log: $ 
  53.  */  

相关内容