有时候在系统中需要一次性下载多个文件,但逐个下载文件比较麻烦。这时候,最好的解决办法是将所有文件打包成一个压缩文件,然后下载这个压缩文件,这样就可以一次性获取所有所需的文件了。

下面是一个名为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以实现多文件批量下载的更多相关文章

  1. Linux下打包压缩war和解压war包 zip和jar

    ============jar================= 把当前目录下的所有文件打包成game.warjar -cvfM0 game.war ./ -c   创建war包-v   显示过程信息 ...

  2. 文件夹生成zip

    package com.leoodata.utils; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.Zi ...

  3. 从CSV文件中读取jpg图片的URL地址并多线程批量下载

    很多时候,我们的网站上传图片时并没有根据内容进行文件夹分类,甚至会直接存储到阿里云的OSS或是七牛云等云存储上.这样,当我们需要打包图片时,就需要从数据库找寻分类图片,通过CURL进行下载.我最近刚刚 ...

  4. Python 读写文件 小应用:生成随机的测验试卷文件

    去年学习了python的读写文件部分,了解了python读写的常用模块os.shelve,今天准备把课后作业试着自己做一下 目标:1)生成35份试卷.每个试卷有50道选择题 2)为了防止有学生作弊,需 ...

  5. ASP.NET Core 上传文件到共享文件夹

    参考资料:ASP.NET 上传文件到共享文件夹 创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html 一.配置上传文件相关参数并读取 ...

  6. ASP.NET 上传文件到共享文件夹

    创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html 上传文件代码 web.config <!--上传文件配置,UploadP ...

  7. 利用SkyDrive Pro 迅速批量下载SharePoint Server 上已上传的文件

    在上一篇<SharePoint Server 2013 让上传文件更精彩>,我们一起了解了如何快速的方便的上传批量文件到SharePoint Server 2013 ,而在这一篇日志中您将 ...

  8. php中soap的使用实例以及生成WSDL文件,提供自动生成WSDL文件的类库——SoapDiscovery.class.php类

    1. web service普及: Webservice soap wsdl区别之个人见解 Web Service实现业务诉求:  Web Service是真正“办事”的那个,提供一种办事接口的统称. ...

  9. java/resteasy批量下载存储在阿里云OSS上的文件,并打包压缩

    现在需要从oss上面批量下载文件并压缩打包,搜了很多相关博客,均是缺胳膊少腿,要么是和官网说法不一,要么就压缩包工具类不给出 官方API https://help.aliyun.com/documen ...

  10. linux使用tar命令打包压缩时排除某个文件夹或文件

    今天在使用tar命令进行文件夹打包压缩的时候,需要打包压缩masalaPage目录,但是该目录中的2017,2016两个目录中的文件不进行打包压缩 所以通常使用的tar -zcvf masalaPag ...

随机推荐

  1. 【Azure 环境】Windows中安装Python azure-eventhub-checkpointstoreblob-aio模块时出错 ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory:

    问题描述 在使用Python代码接受EventHub的消息时,根据文档要求安装azure-eventhub-checkpointstoreblob-aio模块时,出现了如下错误: ERROR: Cou ...

  2. 【Azure 应用程序见解】在Azure门户中,创建App Service(应用服务)时,无法一起创建Application Insights的问题

    问题描述 创建Web应用时启用监视的问题.Azure管理员(Admin)用户下分配了 一个子用户.但是在使用子用户创建WEB应用的时候,启用 Application Insights 选项的 &quo ...

  3. Frechet Inception Distance

    (以下内容重新更新,主要讲解FID的意义,为何FID能够表示生成图像的多样性和质量,为什么FID越小,则图像多样性越好,质量也越好) 在计算FID中我们也同样使用inception network网络 ...

  4. 十: SQL执行流程

    SQL执行流程 1. MySQL 中的 SQL执行流程 MySQL的查询流程: 1.1 查询缓存 Server 如果在查询缓存中发现了这条 SQL 语句,就会直接将结果返回给客户端:如果没 有,就进入 ...

  5. 案例8:将"picK"的大小写互换

    最终输出结果为PICk. 需要先计算两个字母之间的间隔,比如a和A之间的间隔为多少. 然后在将大写字母转换为小写字母,加上间隔的值: 将小写字母转换为大写字母,减去间隔的值. 示例代码如下: #def ...

  6. vite 子项目 热部署 通过nginx,和父项目端口号不同,导致热更新的websocket报错的解决方案

    vite 子项目 热部署 通过nginx,和父项目端口号不同,导致热更新的websocket报错的解决方案 我的父项目端口号是8888 子项目端口号是 8013 这里报错的原因就是,热更新的webso ...

  7. vscode 切换页签快捷键 自定义 Ctrl+H Ctrl+L 左右切换

    今天需要整理写资料,需要在多个页签之间切换,发现自定义了快捷. 好久不用这个快捷键,都快忘了. vscode 切换页签快捷键 自定义 Ctrl+H Ctrl+L 左右切换

  8. linux 前端 jenkins打包失败 permission 权限安装 root 安装nodejs,没有权限,另一个账号,需要chmod将文件权限打开

    linux 前端 jenkins打包失败 permission 权限安装 root 安装nodejs,没有权限,另一个账号,需要chmod将文件权限打开 开始以为nodejs版本问题 最后发现是安装n ...

  9. Java GUI swing 可执行程序 jar (java -jar)idea

    创建项目 可以用maven idea设置 into 那个 参考资料 Java 基础 https://www.liaoxuefeng.com/wiki/1252599548343744/12604545 ...

  10. day06-SpringMVC底层机制简单实现-02

    SpringMVC底层机制简单实现-02 https://github.com/liyuelian/springmvc-demo.git 4.任务3-从web.xml动态获取容器配置文件 4.1分析 ...