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

下面是一个名为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 App Service for Linux】Linux Web App如何安装系统未安装的包

    问题描述 Linux Web App中如何安装系统默认未安装的包,如何来执行如 apt install XXX命令呢?现在遇见的问题时,通过Azure App Service门户中的SSH登录后,执行 ...

  2. 【Azure 应用服务】App Service For Linux 环境中,如何从App Service中获取GitHub私有库(Private Repos)的Deploy Key(RSA key)呢?

    问题描述 为App Service For Linux配置CI/CD,源代码在GitHub私有库中,在发布时候报错 Cannot find SourceControlToken with name B ...

  3. 【Azure 存储服务】关于对Azure Storage Account 的 Folder 权限管理和设定

    问题描述 在一个storage account下面有很多folder,需要对不同的folder设置不同的权限给到不同的用户来访问使用,怎么样设定比较合理? 问题解答 一:可以使用SAS共享访问签名进行 ...

  4. Java 设计模式----单例模式--饿汉式

    1 package com.bytezreo.singleton; 2 3 /** 4 * 5 * @Description 单例设计模式 例子-----饿汉式 6 * @author Bytezer ...

  5. centos7通过配置hosts.allow和hosts.deny限制登陆

    etc/hosts.allow和/etc/hosts.deny两个文件是控制远程访问设置的,通过他可以允许或者拒绝某个ip或者ip段的客户访问linux的某项服务. 我们通常只对管理员开放SSH登录, ...

  6. Nginx-负载均衡系列

    综合架构-负载均衡系列 目录 综合架构-负载均衡系列 一个新的开始 一 代理模块 proxy 2.1 概述 2.2 正向代理用户 2.3 反向代理 2.4 反向代理环境准备 2.5 反正代理指令 二 ...

  7. 浏览器的文件访问 API 入门(英文)- 资料

    浏览器的文件访问 API 入门(英文)- 资料 浏览器现在提供了文件访问 API(File System Access API),允许网页 JS 脚本读写本地文件,本文是一个详细的介绍.另外,也可以参 ...

  8. 《TencentNCNN系列》 之param文件(网络结构文件)格式分析

    PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明   本文作为本人csdn blog的主站的备份.(Bl ...

  9. 1、Azure Devops之什么是Azure DevOps

    什么是Azure DevOps 1.师出名门:是微软推出的一个集项目管理.开发管理.测试管理的一个服务套件. 2.历史:前身是微软在2005年推出的Team foundation Server一个专门 ...

  10. CSS(语义化标签、多媒体标签、新表单元素、属性选择器、结构伪类选择器、伪元素选择器、盒子模型、滤镜、calc函数、过渡)

    一.HTML5新特性 概述 HTML5 的新增特性主要是针对于以前的不足,增加了一些新的标签.新的表单和新的表单属性等. 这些新特性都有兼容性问题,基本是 IE9+ 以上版本的浏览器才支持,如果不考虑 ...