星空网 > 软件开发 > Java

JAVA中的deflate压缩实现

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

 1   /** 2    *  3    * @param inputByte 4    *      待解压缩的字节数组 5    * @return 解压缩后的字节数组 6    * @throws IOException 7   */ 8   public static byte[] uncompress(byte[] inputByte) throws IOException { 9     int len = 0;10     Inflater infl = new Inflater();11     infl.setInput(inputByte);12     ByteArrayOutputStream bos = new ByteArrayOutputStream();13     byte[] outByte = new byte[1024];14     try {15       while (!infl.finished()) {16         // 解压缩并将解压缩后的内容输出到字节输出流bos中17         len = infl.inflate(outByte);18         if (len == 0) {19           break;20         }21         bos.write(outByte, 0, len);22       }23       infl.end();24     } catch (Exception e) {25       //26     } finally {27       bos.close();28     }29     return bos.toByteArray();30   }31 32   /**33    * 压缩.34    * 35    * @param inputByte36    *      待压缩的字节数组37    * @return 压缩后的数据38    * @throws IOException39   */40   public static byte[] compress(byte[] inputByte) throws IOException {41     int len = 0;42     Deflater defl = new Deflater();43     defl.setInput(inputByte);44     defl.finish();45     ByteArrayOutputStream bos = new ByteArrayOutputStream();46     byte[] outputByte = new byte[1024];47     try {48       while (!defl.finished()) {49         // 压缩并将压缩后的内容输出到字节输出流bos中50         len = defl.deflate(outputByte);51         bos.write(outputByte, 0, len);52       }53       defl.end();54     } finally {55       bos.close();56     }57     return bos.toByteArray();58   }59 60   public static void main(String[] args) {61     try {62       FileInputStream fis = new FileInputStream("D:\\testdeflate.txt");63       int len = fis.available();64       byte[] b = new byte[len];65       fis.read(b);66       byte[] bd = compress(b);67       // 为了压缩后的内容能够在网络上传输,一般采用Base64编码68       String encodestr = Base64.encodeBase64String(bd);69       byte[] bi = uncompress(Base64.decodeBase64(encodestr));70       FileOutputStream fos = new FileOutputStream("D:\\testinflate.txt");71       fos.write(bi);72       fos.flush();73       fos.close();74       fis.close();75     } catch (Exception e) {76       //77     }78   }

 




原标题:JAVA中的deflate压缩实现

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

70亿次搜索,80%的用户都买了这类产品!:https://www.ikjzd.com/articles/137034
涨了60%!做户外运动产品,都有一颗“初心”:https://www.ikjzd.com/articles/137035
2025年电商快件基本不再二次包装:https://www.ikjzd.com/articles/137037
字节跳动惜败?!蚂蚁等财团获得新加坡数字银行牌照,东南亚电子支付将迎新突破:https://www.ikjzd.com/articles/137038
亚马逊卖家如何提早防范侵权问题?:https://www.ikjzd.com/articles/137039
关于使用亚马逊变体及变体滥用的常见问题解答!:https://www.ikjzd.com/articles/13704
大福地快捷酒店预订 大福酒店怎么走:https://www.vstour.cn/a/365187.html
三亚有哪些酒店值得入住?:https://www.vstour.cn/a/366173.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流