zoukankan      html  css  js  c++  java
  • 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(" 原始的字符串为------->" + str);  
    23.          float len0=str.length();  
    24.          System.out.println("原始的字符串长度为------->"+len0);  
    25.    
    26.          String ys = compress(str);  
    27.          System.out.println(" 压缩后的字符串为----->" + ys);  
    28.          float len1=ys.length();  
    29.          System.out.println("压缩后的字符串长度为----->" + len1);  
    30.    
    31.          String jy = unCompress(ys);  
    32.          System.out.println(" 解压缩后的字符串为--->" + jy);  
    33.          System.out.println("解压缩后的字符串长度为--->"+jy.length());  
    34.            
    35.          System.out.println(" 压缩比例为"+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.  }  
  • 相关阅读:
    整数转换成字符
    html总结(一)
    ssh服务
    原码反码补码图形化注意
    关于副本机制
    win8设置自动关机
    python制作的翻译器基于爬取百度翻译【笔记思路】
    python多线程扫描爆破网站服务器思路【笔记】
    用python实现多线程爬取影视网站全部视频方法【笔记】
    利用Python3的requests和re库爬取猫眼电影笔记
  • 原文地址:https://www.cnblogs.com/zengdingxin/p/3183947.html
Copyright © 2011-2022 走看看