有時候在系統(tǒng)中需要一次性下載多個文件,但逐個下載文件比較麻煩。這時候,最好的解決辦法是將所有文件打包成一個壓縮文件,然后下載這個壓縮文件,這樣就可以一次性獲取所有所需的文件了。
下面是一個名為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并創(chuàng)建文件
*
* @param sourceFilePath
* @param zipFilePath
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath) throws IOException {
createLocalCompressFile(sourceFilePath, zipFilePath, null);
}
/**
* 將文件打包到zip并創(chuàng)建文件
*
* @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對應(yīng)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<>();//記錄單個合同號文件夾下每個文件名稱出現(xiàn)的次數(shù)(對重復(fù)文件名重命名)
for (FileInfo document : documentListEntry.getValue()) {
try {
//防止單個文件夾下文件名重復(fù) 對重復(fù)的文件進行重命名
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);
}
}
/**
* 通過網(wǎng)絡(luò)請求下載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();
}
}
/**
* 通過網(wǎng)絡(luò)請求下載zip
*
* @param sourceFilePath 需要壓縮的文件路徑
* @param response HttpServletResponse
* @throws IOException
*/
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response) throws IOException {
httpDownloadCompressFile(sourceFilePath, response, null);
}
/**
* 檢查文件名是否已經(jīng)存在,如果存在,就在文件名后面加上“(1)”,如果文件名“(1)”也存在,則改為“(2)”,以此類推。如果文件名不存在,就直接創(chuàng)建一個新文件。
*
* @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 {
//在本地創(chuàng)建壓縮文件
CompressUtil.createLocalCompressFile("D:\\書籍\\電子書\\醫(yī)書", "D:\\test");
}
壓縮并在本地生成文件驗證結(jié)果:
壓縮文件并通過http請求下載:文章來源:http://www.zghlxwxcb.cn/news/detail-464290.html
/**
* @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請求下載驗證結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-464290.html
到了這里,關(guān)于Java實現(xiàn)打包壓縮文件或文件夾生成zip以實現(xiàn)多文件批量下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!