当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA中的deflate压缩实现方法

JAVA中的deflate压缩实现方法

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

在文件的传输过程中,为了使大文件能够更加方便快速的传输,一般采用压缩的办法来对文件压缩后再传输,java中的java.util.zip包中的deflater和inflater类为使用者提供了deflate算法的压缩功能,以下是自已编写的压缩和解压缩实现,并以压缩文件内容为例说明,其中涉及的具体方法可查看jdk的api了解说明。

/**
   * 
   * @param inputbyte
   *      待解压缩的字节数组
   * @return 解压缩后的字节数组
   * @throws ioexception
   */
  public static byte[] uncompress(byte[] inputbyte) throws ioexception {
    int len = 0;
    inflater infl = new inflater();
    infl.setinput(inputbyte);
    bytearrayoutputstream bos = new bytearrayoutputstream();
    byte[] outbyte = new byte[1024];
    try {
      while (!infl.finished()) {
        // 解压缩并将解压缩后的内容输出到字节输出流bos中
        len = infl.inflate(outbyte);
        if (len == 0) {
          break;
        }
        bos.write(outbyte, 0, len);
      }
      infl.end();
    } catch (exception e) {
      //
    } finally {
      bos.close();
    }
    return bos.tobytearray();
  }

  /**
   * 压缩.
   * 
   * @param inputbyte
   *      待压缩的字节数组
   * @return 压缩后的数据
   * @throws ioexception
   */
  public static byte[] compress(byte[] inputbyte) throws ioexception {
    int len = 0;
    deflater defl = new deflater();
    defl.setinput(inputbyte);
    defl.finish();
    bytearrayoutputstream bos = new bytearrayoutputstream();
    byte[] outputbyte = new byte[1024];
    try {
      while (!defl.finished()) {
        // 压缩并将压缩后的内容输出到字节输出流bos中
        len = defl.deflate(outputbyte);
        bos.write(outputbyte, 0, len);
      }
      defl.end();
    } finally {
      bos.close();
    }
    return bos.tobytearray();
  }

  public static void main(string[] args) {
    try {
      fileinputstream fis = new fileinputstream("d:\\testdeflate.txt");
      int len = fis.available();
      byte[] b = new byte[len];
      fis.read(b);
      byte[] bd = compress(b);
      // 为了压缩后的内容能够在网络上传输,一般采用base64编码
      string encodestr = base64.encodebase64string(bd);
      byte[] bi = uncompress(base64.decodebase64(encodestr));
      fileoutputstream fos = new fileoutputstream("d:\\testinflate.txt");
      fos.write(bi);
      fos.flush();
      fos.close();
      fis.close();
    } catch (exception e) {
      //
    }
  }

以上这篇java中的deflate压缩实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网