歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中字符串壓縮的操作

Java中字符串壓縮的操作

日期:2017/3/1 10:31:13   编辑:Linux編程

這段時間項目中碰到一個問題,就是在做頁面操作的時候,要保存的數據長度大於了表定義的字段長度,我們現在的項目是基於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. 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. public static String uncompress(String str) throws IOException {
  22. System.out.println("壓縮之後的字符串大小:"+str.length());
  23. if (str == null || str.length() == 0) {
  24. return str;
  25. }
  26. ByteArrayOutputStream out = new ByteArrayOutputStream();
  27. ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
  28. GZIPInputStream gunzip = new GZIPInputStream(in);
  29. byte[] buffer = new byte[256];
  30. int n;
  31. while ((n = gunzip.read(buffer)) >= 0) {
  32. out.write(buffer, 0, n);
  33. }
  34. return out.toString();
  35. }
  36. public static void main(String[] args) throws IOException {
  37. System.out.println(StringCompression.uncompress(StringCompression.compress(OracleCompressTest.append("i come from china"))));
  38. }
  39. }
  40. /*
  41. *
  42. * History:
  43. *
  44. *
  45. *
  46. * $Log: $
  47. */

Copyright © Linux教程網 All Rights Reserved