温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用java实现一次性压缩多个文件到zip中

发布时间:2021-09-27 09:33:37 来源:亿速云 阅读:127 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“如何使用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.代码

/*** @Title: compress* @Description: TODO* @param filePaths 需要压缩的文件地址列表(绝对路径)* @param zipFilePath 需要压缩到哪个zip文件(无需创建这样一个zip,只需要指定一个全路径)* @param keepDirStructure 压缩后目录是否保持原目录结构* @throws IOException* @return int  压缩成功的文件个数*/public static int compress(List<String> 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<String> sourceFilePaths = new ArrayList<String>();     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实现一次性压缩多个文件到zip中”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI