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 ...
随机推荐
- 使用OpenTelemetry进行监控
工具介绍 注意:该部分介绍摘抄自:https://www.aiwanyun.cn/archives/174 Prometheus.Grafana.Node Exporter 和Alertmanager ...
- 用Pandoc生成TXT格式的目录
我一直使用Markdown格式写作,使用Pandoc生成PDF和Word格式的文档.Pandoc能生成很好的章节和目录,但有时候,也需要生成TXT格式的目录,今天就尝试了一下. 由于我写的内容章节比较 ...
- Java 如何自定义异常类
1 package com.bytezero.throwable; 2 3 /** 4 * 5 * @Description 如何自定义异常类 6 * @author Bytezero·zhengle ...
- Java 手动抛异常
1 package com.bytezero.throwable; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 impor ...
- 使用 Docker 部署 GLPI 资产管理系统
1)GLPI 介绍 GLPI 简介 参考: https://github.com/glpi-project/glpi 官方文档:https://glpi-project.org/documentati ...
- Springboot-1.5.10.RELEASE 升级到 2.2.4.RELEASE版本遇到的一些问题总结
由于现在springboot的主流版本都已经是2.x的了,因此自己也打算将项目中使用的springboot1.5.10升级到2.2.4这个版本. 自己也能够预料得到,在升级过程中肯定会遇到各种各样的问 ...
- vscode 格式化 vue 等文件的 配置 eslint vetur prettier Beautify
需求 自动格式化需求 多行回车 合并一行,去分号 最后一个逗号,自动删除,符合eslint 结果 虽然能用了,但是 百度好几个方案,也不知道哪个对哪个,太忙没时间弄了. 配置文件记录 eslint 得 ...
- 【easy52pojie】一款方便看吾爱论坛帖子的爬虫程序
众所周知吾爱论坛一页最多显示十来条回帖,且间隔很大,每页的信息密度太低了.在帖子很庞大的情况下,一页一页翻页,着实有点痛苦. 故简单敲敲代码,使用request xpath技术做了一个论坛帖子回复查看 ...
- 精通 Grails: 测试 Grails 应用程序
排除 bug,构建可执行文档 Grails 可以轻松确保您的应用程序从始至终都远离 bug.这还有另一个好处,您可以利用测试代码生成一组通常是最新的可执行文档.本月 Grails 专家 Scott D ...
- jsp相对路径绝对路径
jsp相对路径绝对路径 很长一段时间纠结过JSP中的相对路径和绝对路径,也研究过一段时间,今天趁着有点时间,记下来,也有大家分享一下. 1)我们先来理解一下相对路径 首先还是我们的开始,建一个WEB项 ...