1.工具类
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author 张小张
* @describe 压缩多个文件
* @date 2023/07/18 18:10
*/
public class ZipUtils {
public static void downloadAndZipFiles(HttpServletResponse response, List<String> filePaths, String zipFileName) {
try {
// 设置响应头,告诉浏览器这是一个压缩文件,用于下载
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
// 创建ZipOutputStream对象
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
Map<String, Integer> existingFileNames = new HashMap<>();
// 将文件逐个添加到压缩包中
for (String filePath : filePaths) {
File file = new File(filePath);
if (file.exists()) {
addToZip(zipOut, file, existingFileNames);
}
}
// 关闭ZipOutputStream
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addToZip(ZipOutputStream zipOut, File file, Map<String, Integer> existingFileNames) throws IOException {
if (file.isFile()) {
FileInputStream fis = new FileInputStream(file);
// 获取文件名,并对文件名进行处理
String fileName = file.getName();
fileName = removeContentBetweenUnderscoreAndDot(fileName);
// 处理重名文件
if (existingFileNames.containsKey(fileName)) {
int count = existingFileNames.get(fileName);
count++;
fileName = addCountToFileName(fileName, count);
existingFileNames.put(fileName, count);
} else {
existingFileNames.put(fileName, 1);
}
// 添加到压缩包
zipOut.putNextEntry(new ZipEntry(fileName));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
zipOut.closeEntry();
}
}
private static String removeContentBetweenUnderscoreAndDot(String fileName) {
// 查找第一个'_'的位置
int underscoreIndex = fileName.indexOf('_');
// 查找第一个'.'的位置
int dotIndex = fileName.indexOf('.');
// 如果找到了'_'和'.',并且'_'在'.'之前,执行去除操作
if (underscoreIndex != -1 && dotIndex != -1 && underscoreIndex < dotIndex) {
// 获取'_'和'.'之间的内容
String contentToRemove = fileName.substring(underscoreIndex, dotIndex);
// 替换掉'_'和'.'之间的内容为空字符串
fileName = fileName.replace(contentToRemove, "");
}
return fileName;
}
private static String addCountToFileName(String fileName, int count) {
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex != -1) {
String name = fileName.substring(0, dotIndex);
String extension = fileName.substring(dotIndex);
return name + "(" + count + ")" + extension;
} else {
return fileName + "(" + count + ")";
}
}
}
2.调用
//filePaths:文件url。 zipFileName:下载的压缩包名字
List<String> filePaths = new ArrayList<String>();
filePaths.add("opt/home/file1.xls");
filePaths.add("opt/home/file2.xls");
String zipFileName = "压缩包名字" + searchParam.getType() + ".zip";
ZipUtils.downloadAndZipFiles(response, filePaths, zipFileName);