Java 壓縮字符串


1.引言

最近在做項目中,平台提供一個http服務給其他系統調用,然后我接收到其他系統的json格式的報文后去解析,然后用拿到的數據去調用corba服務,我再把corba的返回值封裝完成json字符串返回給外部系統。遇到一個接口去調用corba服務,然后corba返回的數據經過封裝后字符串的長度達到7M左右,導致http客戶端無法正常的接收完所有的數據。你可能會說這個接口設計的不合理,為什么不增加查詢條件把查詢條件范圍縮小一點?但是,這個不是本節要討論的內容,主要是因為corba服務已經發布用了很久且不在此次項目改造范圍之內,再者這個corba服務已經上線用了N久,輕易的改變可能會導致未知的錯誤。簽於此,我想到可以把json格式的字符串給壓縮,然后客戶端再解壓。(一是字符串的壓縮比例比較的高,二是字符串的壓縮和解壓實現起來也比較簡單)。雖然,最后沒有用到字符串的壓縮和解壓的方式,而是修改客戶端(1.http客戶端進一步精確查詢條件 2.讀取返回數據流采用循環讀取的方式)來解決此問題,我還是把字符串的壓縮和解壓做一下簡單的記錄。

2.關於壓縮與解壓

壓縮算法有多種,我說知道和接觸有java I/O自帶的zip和gzip兩種方式。

本節主要來簡單介紹一下在系統交互之間遇到大容量的字符串數據交互時,采用一端壓縮,另一端再解壓的方式來發送和接收數據。

關於此次的壓縮和解壓用到的主要就是GZIPOutputStream和GZIPInputStream類,此類的相關介紹在JDK中有詳細的介紹,這里就不再累述了

3.代碼如下:

  1.    
  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.  /**  
  9.   *   
  10.   *Module:          ZipUtil.java  
  11.   *Description:    對字符串的壓縮及解壓  
  12.   *Company:         
  13.   *Author:           pantp  
  14.   *Date:             May 6, 2012  
  15.   */  
  16.  public class ZipStrUtil {  
  17.    
  18.      public static void main(String[] args) throws IOException {  
  19.          // 字符串超過一定的長度  
  20.          String str = "ABCdef123中文~!@#$%^&*()_+{};/1111111111111111111111111AAAAAAAAAAAJDLFJDLFJDLFJLDFFFFJEIIIIIIIIIIFJJJJJJJJJJJJALLLLLLLLLLLLLLLLLLLLLL" +  
  21.                  "LLppppppppppppppppppppppppppppppppppppppppp===========================------------------------------iiiiiiiiiiiiiiiiiiiiiii";  
  22.          System.out.println("\n原始的字符串為------->" + str);  
  23.          float len0=str.length();  
  24.          System.out.println("原始的字符串長度為------->"+len0);  
  25.    
  26.          String ys = compress(str);  
  27.          System.out.println("\n壓縮后的字符串為----->" + ys);  
  28.          float len1=ys.length();  
  29.          System.out.println("壓縮后的字符串長度為----->" + len1);  
  30.    
  31.          String jy = unCompress(ys);  
  32.          System.out.println("\n解壓縮后的字符串為--->" + jy);  
  33.          System.out.println("解壓縮后的字符串長度為--->"+jy.length());  
  34.            
  35.          System.out.println("\n壓縮比例為"+len1/len0);  
  36.            
  37.          //判斷  
  38.          if(str.equals(jy)){  
  39.              System.out.println("先壓縮再解壓以后字符串和原來的是一模一樣的");  
  40.          }  
  41.      }  
  42.    
  43.      /**  
  44.       * 字符串的壓縮  
  45.       *   
  46.       * @param str  
  47.       *            待壓縮的字符串  
  48.       * @return    返回壓縮后的字符串  
  49.       * @throws IOException  
  50.       */  
  51.      public static String compress(String str) throws IOException {  
  52.          if (null == str || str.length() <= 0) {  
  53.              return str;  
  54.          }  
  55.          // 創建一個新的 byte 數組輸出流  
  56.          ByteArrayOutputStream out = new ByteArrayOutputStream();  
  57.          // 使用默認緩沖區大小創建新的輸出流  
  58.          GZIPOutputStream gzip = new GZIPOutputStream(out);  
  59.          // 將 b.length 個字節寫入此輸出流  
  60.          gzip.write(str.getBytes());  
  61.          gzip.close();  
  62.          // 使用指定的 charsetName,通過解碼字節將緩沖區內容轉換為字符串  
  63.          return out.toString("ISO-8859-1");  
  64.      }  
  65.        
  66.      /**  
  67.       * 字符串的解壓  
  68.       *   
  69.       * @param str  
  70.       *            對字符串解壓  
  71.       * @return    返回解壓縮后的字符串  
  72.       * @throws IOException  
  73.       */  
  74.      public static String unCompress(String str) throws IOException {  
  75.          if (null == str || str.length() <= 0) {  
  76.              return str;  
  77.          }  
  78.          // 創建一個新的 byte 數組輸出流  
  79.          ByteArrayOutputStream out = new ByteArrayOutputStream();  
  80.          // 創建一個 ByteArrayInputStream,使用 buf 作為其緩沖區數組  
  81.          ByteArrayInputStream in = new ByteArrayInputStream(str  
  82.                  .getBytes("ISO-8859-1"));  
  83.          // 使用默認緩沖區大小創建新的輸入流  
  84.          GZIPInputStream gzip = new GZIPInputStream(in);  
  85.          byte[] buffer = new byte[256];  
  86.          int n = 0;  
  87.          while ((n = gzip.read(buffer)) >= 0) {// 將未壓縮數據讀入字節數組  
  88.              // 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此 byte數組輸出流  
  89.              out.write(buffer, 0, n);  
  90.          }  
  91.          // 使用指定的 charsetName,通過解碼字節將緩沖區內容轉換為字符串  
  92.          return out.toString("GBK");  
  93.      }  
  94.    

    /**
    * 根據byte數組,生成文件
    *
    * @param bfile
    * byte數組
    * @param filePath
    * 存儲路徑
    * @param fileName
    * 文件名稱
    * @return true:保存成功 false:保存失敗
    */
    public static boolean getFile(byte[] bfile, String filePath, String fileName) {
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    File file = null;
    boolean result = true;
    try {
    File dir = new File(filePath);
    if (!dir.exists() && dir.isDirectory()) {// 判斷文件目錄是否存在
    dir.mkdirs();
    }
    file = new File(filePath + "\\" + fileName);
    fos = new FileOutputStream(file);
    bos = new BufferedOutputStream(fos);
    bos.write(bfile);
    } catch (Exception e) {
    result = false;
    e.printStackTrace();
    } finally {
    if (bos != null) {
    try {
    bos.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    if (fos != null) {
    try {
    fos.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    }

    return result;
    }

  95.  }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM