Java实现打包压缩文件或文件夹生成zip以实现多文件批量下载
有时候在系统中需要一次性下载多个文件,但逐个下载文件比较麻烦。这时候,最好的解决办法是将所有文件打包成一个压缩文件,然后下载这个压缩文件,这样就可以一次性获取所有所需的文件了。
下面是一个名为CompressUtil的工具类的代码,它提供了一些方法来处理文件压缩和下载操作:
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* @author fhey
* @date 2023-05-11 20:48:28
* @description: 压缩工具类
*/
public class CompressUtil {
private static final Logger logger = LoggerFactory.getLogger(CompressUtil.class);
/**
* 将文件打包到zip并创建文件
*
* @param sourceFilePath
* @param zipFilePath
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath) throws IOException {
createLocalCompressFile(sourceFilePath, zipFilePath, null);
}
/**
* 将文件打包到zip并创建文件
*
* @param sourceFilePath
* @param zipFilePath
* @param zipName
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath, String zipName) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
if(StringUtils.isBlank(zipName)){
zipName = sourceFile.getName();
}
File zipFile = createNewFile(zipFilePath + File.separator + zipName + ".zip");
try (FileOutputStream fileOutputStream = new FileOutputStream(zipFile)) {
compressFile(sourceFile, fileOutputStream);
}
}
/**
* 获取压缩文件流
*
* @param sourceFilePath
* @return ByteArrayOutputStream
* @throws IOException
*/
public static OutputStream compressFile(String sourceFilePath, OutputStream outputStream) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
return compressFile(sourceFile, outputStream);
}
/**
* 获取压缩文件流
*
* @param sourceFile
* @return ByteArrayOutputStream
* @throws IOException
*/
private static OutputStream compressFile(File sourceFile, OutputStream outputStream) throws IOException {
try (CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream)) {
doCompressFile(sourceFile, zipOutputStream, StringUtils.EMPTY);
return outputStream;
}
}
/**
* 处理目录下的文件
*
* @param sourceFile
* @param zipOutputStream
* @param zipFilePath
* @throws IOException
*/
private static void doCompressFile(File sourceFile, ZipOutputStream zipOutputStream, String zipFilePath) throws IOException {
// 如果文件是隐藏的,不进行压缩
if (sourceFile.isHidden()) {
return;
}
if (sourceFile.isDirectory()) {//如果是文件夹
handDirectory(sourceFile, zipOutputStream, zipFilePath);
} else {//如果是文件就添加到压缩包中
try (FileInputStream fileInputStream = new FileInputStream(sourceFile)) {
//String fileName = zipFilePath + File.separator + sourceFile.getName();
String fileName = zipFilePath + sourceFile.getName();
addCompressFile(fileInputStream, fileName, zipOutputStream);
//String fileName = zipFilePath.replace("\\", "/") + "/" + sourceFile.getName();
//addCompressFile(fileInputStream, fileName, zipOutputStream);
}
}
}
/**
* 处理文件夹
*
* @param dir 文件夹
* @param zipOut 压缩包输出流
* @param zipFilePath 压缩包中的文件夹路径
* @throws IOException
*/
private static void handDirectory(File dir, ZipOutputStream zipOut, String zipFilePath) throws IOException {
File[] files = dir.listFiles();
if (ArrayUtils.isEmpty(files)) {
ZipEntry zipEntry = new ZipEntry(zipFilePath + dir.getName() + File.separator);
zipOut.putNextEntry(zipEntry);
zipOut.closeEntry();
return;
}
for (File file : files) {
doCompressFile(file, zipOut, zipFilePath + dir.getName() + File.separator);
}
}
/**
* 获取压缩文件流
*
* @param documentList 需要压缩的文件集合
* @return ByteArrayOutputStream
*/
public static OutputStream compressFile(List<FileInfo> documentList, OutputStream outputStream) {
Map<String, List<FileInfo>> documentMap = new HashMap<>();
documentMap.put("", documentList);
return compressFile(documentMap, outputStream);
}
/**
* 将文件打包到zip
*
* @param documentMap 需要下载的附件集合 map的key对应zip里的文件夹名
* @return ByteArrayOutputStream
*/
public static OutputStream compressFile(Map<String, List<FileInfo>> documentMap, OutputStream outputStream) {
CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream);
try {
for (Map.Entry<String, List<FileInfo>> documentListEntry : documentMap.entrySet()) {
String dirName = documentMap.size() > 1 ? documentListEntry.getKey() : "";
Map<String, Integer> fileNameToLen = new HashMap<>();//记录单个合同号文件夹下每个文件名称出现的次数(对重复文件名重命名)
for (FileInfo document : documentListEntry.getValue()) {
try {
//防止单个文件夹下文件名重复 对重复的文件进行重命名
String documentName = document.getFileName();
if (fileNameToLen.get(documentName) == null) {
fileNameToLen.put(documentName, 1);
} else {
int fileLen = fileNameToLen.get(documentName) + 1;
fileNameToLen.put(documentName, fileLen);
documentName = documentName + "(" + fileLen + ")";
}
String fileName = documentName + "." + document.getSuffix();
if (StringUtils.isNotBlank(dirName)) {
fileName = dirName + File.separator + fileName;
}
addCompressFile(document.getFileInputStream(), fileName, zipOutputStream);
} catch (Exception e) {
logger.info("filesToZip exception :", e);
}
}
}
} catch (Exception e) {
logger.error("filesToZip exception:" + e.getMessage(), e);
}
return outputStream;
}
/**
* 将单个文件写入文件压缩包
*
* @param inputStream 文件输入流
* @param fileName 文件在压缩包中的相对全路径
* @param zipOutputStream 压缩包输出流
*/
private static void addCompressFile(InputStream inputStream, String fileName, ZipOutputStream zipOutputStream) {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = bufferedInputStream.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
//System.out.println("map size, value is " + RamUsageEstimator.sizeOf(zipOutputStream));
} catch (Exception e) {
logger.info("addFileToZip exception:", e);
throw new RuntimeException(e);
}
}
/**
* 通过网络请求下载zip
*
* @param sourceFilePath 需要压缩的文件路径
* @param response HttpServletResponse
* @param zipName 压缩包名称
* @throws IOException
*/
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response, String zipName) throws IOException {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFilePath + "不存在!");
}
if(StringUtils.isBlank(zipName)){
zipName = sourceFile.getName();
}
try (ServletOutputStream servletOutputStream = response.getOutputStream()){
CompressUtil.compressFile(sourceFile, servletOutputStream);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
servletOutputStream.flush();
}
}
public static void httpDownloadCompressFileOld(String sourceFilePath, HttpServletResponse response, String zipName) throws IOException {
try (ServletOutputStream servletOutputStream = response.getOutputStream()){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] zipBytes = byteArrayOutputStream.toByteArray();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
response.setContentLength(zipBytes.length);
servletOutputStream.write(zipBytes);
servletOutputStream.flush();
}
}
/**
* 通过网络请求下载zip
*
* @param sourceFilePath 需要压缩的文件路径
* @param response HttpServletResponse
* @throws IOException
*/
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response) throws IOException {
httpDownloadCompressFile(sourceFilePath, response, null);
}
/**
* 检查文件名是否已经存在,如果存在,就在文件名后面加上“(1)”,如果文件名“(1)”也存在,则改为“(2)”,以此类推。如果文件名不存在,就直接创建一个新文件。
*
* @param filename 文件名
* @return File
*/
public static File createNewFile(String filename) {
File file = new File(filename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
String base = filename.substring(0, filename.lastIndexOf("."));
String ext = filename.substring(filename.lastIndexOf("."));
int i = 1;
while (true) {
String newFilename = base + "(" + i + ")" + ext;
file = new File(newFilename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
i++;
}
}
return file;
}
}
FileInfo类代码:
/**
* @author fhey
* @date 2023-05-11 21:01:26
* @description: TODO
*/
@Data
public class FileInfo {
private InputStream fileInputStream;
private String suffix;
private String fileName;
private boolean isDirectory;
}
测试压缩并在本地生成文件:
public static void main(String[] args) throws Exception {
//在本地创建压缩文件
CompressUtil.createLocalCompressFile("D:\\书籍\\电子书\\医书", "D:\\test");
}
压缩并在本地生成文件验证结果:

压缩文件并通过http请求下载:
/**
* @author fhey
*/
@RestController
public class TestController {
@GetMapping(value = "/testFileToZip")
public void testFileToZip(HttpServletResponse response) throws IOException {
String zipFileName = "myFiles";
String sourceFilePath = "D:\\picture";
CompressUtil.httpDownloadCompressFile(sourceFilePath,response, zipFileName);
}
}
压缩文件并通过http请求下载验证结果:

Java实现打包压缩文件或文件夹生成zip以实现多文件批量下载的更多相关文章
- Linux下打包压缩war和解压war包 zip和jar
============jar================= 把当前目录下的所有文件打包成game.warjar -cvfM0 game.war ./ -c 创建war包-v 显示过程信息 ...
- 文件夹生成zip
package com.leoodata.utils; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.Zi ...
- 从CSV文件中读取jpg图片的URL地址并多线程批量下载
很多时候,我们的网站上传图片时并没有根据内容进行文件夹分类,甚至会直接存储到阿里云的OSS或是七牛云等云存储上.这样,当我们需要打包图片时,就需要从数据库找寻分类图片,通过CURL进行下载.我最近刚刚 ...
- Python 读写文件 小应用:生成随机的测验试卷文件
去年学习了python的读写文件部分,了解了python读写的常用模块os.shelve,今天准备把课后作业试着自己做一下 目标:1)生成35份试卷.每个试卷有50道选择题 2)为了防止有学生作弊,需 ...
- ASP.NET Core 上传文件到共享文件夹
参考资料:ASP.NET 上传文件到共享文件夹 创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html 一.配置上传文件相关参数并读取 ...
- ASP.NET 上传文件到共享文件夹
创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html 上传文件代码 web.config <!--上传文件配置,UploadP ...
- 利用SkyDrive Pro 迅速批量下载SharePoint Server 上已上传的文件
在上一篇<SharePoint Server 2013 让上传文件更精彩>,我们一起了解了如何快速的方便的上传批量文件到SharePoint Server 2013 ,而在这一篇日志中您将 ...
- php中soap的使用实例以及生成WSDL文件,提供自动生成WSDL文件的类库——SoapDiscovery.class.php类
1. web service普及: Webservice soap wsdl区别之个人见解 Web Service实现业务诉求: Web Service是真正“办事”的那个,提供一种办事接口的统称. ...
- java/resteasy批量下载存储在阿里云OSS上的文件,并打包压缩
现在需要从oss上面批量下载文件并压缩打包,搜了很多相关博客,均是缺胳膊少腿,要么是和官网说法不一,要么就压缩包工具类不给出 官方API https://help.aliyun.com/documen ...
- linux使用tar命令打包压缩时排除某个文件夹或文件
今天在使用tar命令进行文件夹打包压缩的时候,需要打包压缩masalaPage目录,但是该目录中的2017,2016两个目录中的文件不进行打包压缩 所以通常使用的tar -zcvf masalaPag ...
随机推荐
- CYQ.Data 支持 KingbaseES人大金仓数据库
KingbaseES人大金仓数据库介绍: KingbaseES是一种关系型数据库管理系统,也被称为人大金仓数据库.KingbaseES 是北京人大金仓信息技术股份有限公司研发的,具有自主知识产权的通用 ...
- java 携带session 前台传递cookie 跨域解决方案 vue + java
前台 axios 设置 withCredentials: true 后台设置 跨域 header("Access-Control-Allow-Origin","源地址&q ...
- gyroflow.xyz - 视频防抖 支持相机 gopro 不支持手机视频 - 软件推荐
gyroflow.xyz - 视频防抖 支持相机 gopro 不支持手机视频 - 软件推荐 https://gyroflow.xyz/ https://github.com/gyroflow/gyro ...
- etcd每个节点都存储了完整的键值对数据集,为什么扩容etcd集群仍可分散存储压力?
etcd每个节点都存储了完整的键值对数据集,这主要是为了确保数据的一致性和高可用性.在这种设计下,任何一个节点都可以处理读取请求,并在本地提供数据,从而无需跨节点通信.这种冗余的数据存储方式也增加了系 ...
- c++的IO类
CPP的IO类 继承图: IO对象不能拷贝或赋值 istream in = cin; //错! istream &in = cin; //正确! IO对象的状态 strm::good:读正常 ...
- 软件开发、持续集成(CI)、持续交付(CD)、持续部署(CD) 和 版本管理(Version Control) 的理解和思考
PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明 本文作为本人csdn blog的主站的备份.(Bl ...
- 宁波市ctf线下赛awd总结
这是第四届宁波市ctf比赛的线下awd经验总结. 由于主办方的服务器出错,原定于14:00开始的比赛,最后17:30才开始,一直打到20:30. 并且突然改了一部分比赛方式,取消了前30分钟的加固时间 ...
- Java博客大汇总
目录介绍 01.Java基础[30篇] 02.面向对象[15篇] 03.数据结构[27篇] 04.IO流知识[11篇] 05.线程进程[9篇] 06.虚拟机[12篇] 07.类的加载[7篇] 08.反 ...
- .Net 8.0 除gRPC之外的另一个选择,IceRPC之快束开始HelloWorld
作者引言 很高兴啊,我们来到了第一篇,程序员的HelloWorld,快速开始RPC之游 快速入门 演示如何在几分钟内,使用IceRPC,构建和运行一个完整的客户端-服务器(C/S)应用程序. 必要条件 ...
- 开发必会系列:《深入理解JVM(第二版)》读书笔记
一 开始前 HotSpot:http://xiaomogui.iteye.com/blog/857821 http://blog.csdn.net/u011521890/article/detail ...