栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA中的deflate压缩实现方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA中的deflate压缩实现方法

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


  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();
  }

  
  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压缩实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号