java如何使用zip压缩

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 多平台发布

posted @ 2023-11-06 10:13  拾光师  阅读(75)  评论(0编辑  收藏  举报  来源