java中GZIP压缩解压类使用实例

  

<强> java中GZIP压缩解压类使用实例

  

,,当我们客户端与服务端进行数据传输时需要走流量,为了节省流量我们常常需要写一个压缩类对数据进行压缩。

  

<>强实例代码:

        进口java.io.ByteArrayInputStream;   进口java.io.ByteArrayOutputStream;   进口java.io.IOException;   进口java.util.zip.GZIPInputStream;   进口java.util.zip.GZIPOutputStream;/* *   * GZIP压缩解压类   */公开课MessageGZIP {      私有静态字符串编码=" utf - 8 ",//癷so - 8859 - 1”      公共字符串getEncode () {   返回编码;   }/*   *设置编码,默认编码:utf - 8   */公共空间setEncode(字符串编码){   MessageGZIP。编码=编码;   }/*   *字符串压缩为字节数组   */公共静态byte [] compressToByte (String str) {   如果(str==null | | str.length ()==0) {   返回null;   }   ByteArrayOutputStream=新ByteArrayOutputStream ();   GZIPOutputStream gzip;   尝试{   gzip=new GZIPOutputStream(出);   gzip.write (str.getBytes(编码);   gzip.close ();   }捕捉(IOException e) {   e.printStackTrace ();   }   返回out.toByteArray ();   }/*   *字符串压缩为字节数组   */公共静态byte [] compressToByte (String str,字符串编码){   如果(str==null | | str.length ()==0) {   返回null;   }   ByteArrayOutputStream=新ByteArrayOutputStream ();   GZIPOutputStream gzip;   尝试{   gzip=new GZIPOutputStream(出);   gzip.write (str.getBytes(编码));   gzip.close ();   }捕捉(IOException e) {   e.printStackTrace ();   }   返回out.toByteArray ();   }/*   *字节数组解压缩后返回字符串   */公共静态字符串uncompressToString (byte [] b) {   如果(b==null | | b。长度==0){   返回null;   }   ByteArrayOutputStream=新ByteArrayOutputStream ();   ByteArrayInputStream=新ByteArrayInputStream (b);      尝试{   GZIPInputStream gunzip=new GZIPInputStream(的);   byte[]新字节缓冲区=[256];   int n;   在((n=gunzip.read(缓冲))在=0){   出去了。写(缓冲0 n);   }   }捕捉(IOException e) {   e.printStackTrace ();   }   返回out.toString ();   }/*   *字节数组解压缩后返回字符串   */公共静态字符串uncompressToString (byte [] b,字符串编码){   如果(b==null | | b。长度==0){   返回null;   }   ByteArrayOutputStream=新ByteArrayOutputStream ();   ByteArrayInputStream=新ByteArrayInputStream (b);      尝试{   GZIPInputStream gunzip=new GZIPInputStream(的);   byte[]新字节缓冲区=[256];   int n;   在((n=gunzip.read(缓冲))在=0){   出去了。写(缓冲0 n);   }   返回out.toString(编码);   }捕捉(IOException e) {   e.printStackTrace ();   }   返回null;   }   }   之前      

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

java中GZIP压缩解压类使用实例