当前位置: 移动技术网 > IT编程>开发语言>Java > java中GZIP压缩解压类使用实例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

常依云,日怒徽记交给谁,罗通拜师

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

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

实例代码:

import java.io.bytearrayinputstream; 
import java.io.bytearrayoutputstream; 
import java.io.ioexception; 
import java.util.zip.gzipinputstream; 
import java.util.zip.gzipoutputstream; 
 
/** 
 * gzip压缩解压类 
 */ 
public class messagegzip { 
   
  private static string encode = "utf-8";//"iso-8859-1" 
   
  public string getencode() { 
    return encode; 
  } 
 
  /* 
   * 设置 编码,默认编码:utf-8 
   */ 
  public void setencode(string encode) { 
    messagegzip.encode = encode; 
  } 
 
  /* 
   * 字符串压缩为字节数组 
   */ 
  public static byte[] compresstobyte(string str){ 
    if (str == null || str.length() == 0) { 
      return null; 
    } 
    bytearrayoutputstream out = new bytearrayoutputstream(); 
    gzipoutputstream gzip; 
    try { 
      gzip = new gzipoutputstream(out); 
      gzip.write(str.getbytes(encode)); 
      gzip.close(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
    return out.tobytearray(); 
  } 
 
  /* 
   * 字符串压缩为字节数组 
   */ 
  public static byte[] compresstobyte(string str,string encoding){ 
    if (str == null || str.length() == 0) { 
      return null; 
    } 
    bytearrayoutputstream out = new bytearrayoutputstream(); 
    gzipoutputstream gzip; 
    try { 
      gzip = new gzipoutputstream(out); 
      gzip.write(str.getbytes(encoding)); 
      gzip.close(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
    return out.tobytearray(); 
  } 
 
  /* 
   * 字节数组解压缩后返回字符串 
   */ 
  public static string uncompresstostring(byte[] b) { 
    if (b == null || b.length == 0) { 
      return null; 
    } 
    bytearrayoutputstream out = new bytearrayoutputstream(); 
    bytearrayinputstream in = new bytearrayinputstream(b); 
 
    try { 
      gzipinputstream gunzip = new gzipinputstream(in); 
      byte[] buffer = new byte[256]; 
      int n; 
      while ((n = gunzip.read(buffer)) >= 0) { 
        out.write(buffer, 0, n); 
      } 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
    return out.tostring(); 
  } 
 
  /* 
   * 字节数组解压缩后返回字符串 
   */ 
  public static string uncompresstostring(byte[] b, string encoding) { 
    if (b == null || b.length == 0) { 
      return null; 
    } 
    bytearrayoutputstream out = new bytearrayoutputstream(); 
    bytearrayinputstream in = new bytearrayinputstream(b); 
 
    try { 
      gzipinputstream gunzip = new gzipinputstream(in); 
      byte[] buffer = new byte[256]; 
      int n; 
      while ((n = gunzip.read(buffer)) >= 0) { 
        out.write(buffer, 0, n); 
      } 
      return out.tostring(encoding); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
    } 
    return null; 
  } 
} 

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网