java如何使用zip压缩

本文详细介绍了如何在Java中使用ZipInputStream读取和ZipOutputStream写入Zip文档,包括处理文件和目录的压缩过程。
摘要由CSDN通过智能技术生成

zip压缩

zip文档可以以压缩格式存储一个或多个文件,可以使用ZipInputStream读取Zip文档,使用ZipOutputStream来写入到Zip文件中

ZipInputStream读取

ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
// getNextEntry返回描述这个项的ZipEntry的对象
while ((ze = zin.getNextEntry()) != null) {
    // getInputStream获取用于读取该项的输入流
        BufferedReader br = new BufferedReader(
                new InputStreamReader(zf.getInputStream(ze), charset));
  // 业务逻辑 todo
        br.close();
  // closeEntry关闭当前打开的项
    zin.closeEntry();
}
zin.close();

ZipOutputStream写入

ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

File fileWillZip = new File(dir);

if (fileWillZip.exists()) {
    // 需要压缩的文件是文件夹。需要递归进行压缩
    if(fileWillZip.isDirectory()){
        compressZip(zipOut,fileWillZip,fileWillZip.getName());
    } else { // 是文件,直接压缩
        zip(zipOut,fileWillZip,dir);
    }
}
zipOut.closeEntry();
zipOut.close();



private void compressZip(ZipOutputStream zipOutput, File file, String suffixpath) {
        File[] listFiles = file.listFiles();// 列出所有的文件
        for(File fi : listFiles){
            if(fi.isDirectory()){ // 如果是文件夹,继续递归
                if(suffixpath.equals("")){
                    compressZip(zipOutput, fi, fi.getName());
                }else{
                    compressZip(zipOutput, fi, suffixpath + File.separator + fi.getName());
                }
            }else{
                zip(zipOutput, fi, suffixpath);
            }
        }
    }

    public void zip(ZipOutputStream zipOutput, File file, String suffixpath) {
        try {
          // 创建ZipEntry对象
            ZipEntry zEntry = null;
            if(suffixpath.equals("")){
                zEntry = new ZipEntry(file.getName());
            }else{
                zEntry = new ZipEntry(suffixpath + File.separator + file.getName());
            }
          // putNextEntry将给定的ZipEntry中的信息写出到输出流,并定位用于写出数据的流,然后这些数据可以通过write方法写出到这个输出流中
            zipOutput.putNextEntry(zEntry);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[1024];
            int read = 0;
            while((read = bis.read(buffer)) != -1){
                zipOutput.write(buffer, 0, read);
            }
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

https://zhhll.icu/2022/java基础/IO/3.zip压缩/

本文由mdnice多平台发布

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值