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

java实现一次性压缩多个文件到zip中的方法示例

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

java实现一次性压缩多个文件到zip中的方法示例

本文实例讲述了java实现一次性压缩多个文件到zip中的方法。分享给大家供大家参考,具体如下:

1.需要引入包:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.util.StringUtils;

2.代码


public static int compress(List filePaths, String zipFilePath,Boolean keepDirStructure) throws IOException{
     byte[] buf = new byte[1024];
     File zipFile = new File(zipFilePath);
     //zip文件不存在,则创建文件,用于压缩
     if(!zipFile.exists())
zipFile.createNewFile();
     int fileCount = 0;//记录压缩了几个文件?
     try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for(int i = 0; i < filePaths.size(); i++){
  String relativePath = filePaths.get(i);
  if(StringUtils.isEmpty(relativePath)){
    continue;
  }
  File sourceFile = new File(relativePath);//绝对路径找到file
  if(sourceFile == null || !sourceFile.exists()){
    continue;
  }
  FileInputStream fis = new FileInputStream(sourceFile);
  if(keepDirStructure!=null && keepDirStructure){
    //保持目录结构
    zos.putNextEntry(new ZipEntry(relativePath));
  }else{
    //直接放到压缩包的根目录
    zos.putNextEntry(new ZipEntry(sourceFile.getName()));
  }
  //System.out.println("压缩当前文件:"+sourceFile.getName());
  int len;
  while((len = fis.read(buf)) > 0){
    zos.write(buf, 0, len);
  }
  zos.closeEntry();
  fis.close();
  fileCount++;
}
zos.close();
//System.out.println("压缩完成");
     } catch (Exception e) {
e.printStackTrace();
     }
     return fileCount;
}

3.测试

public static void main(String[] args) throws IOException {
     List sourceFilePaths = new ArrayList();
     sourceFilePaths.add("d:/test/C08065.jpg");
     sourceFilePaths.add("d:/test/新建文件夹/C08984.jpg");
     sourceFilePaths.add("d:/test/找不到我.jpg");//试一个找不到的文件
     //指定打包到哪个zip(绝对路径)
     String zipTempFilePath = "D:/test/test.zip";
     //调用压缩
     int s = compress(sourceFilePaths, zipTempFilePath,false);
     System.out.println("成功压缩"+s+"个文件");
}

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

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

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

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