CompressUtil Java Utility for File Compression and Download
This article introduces a Java utility class named CompressUtil that provides methods for compressing files and directories into ZIP archives, handling duplicate filenames, creating new files safely, and offering HTTP endpoints for downloading the generated ZIP files in a single request.
Sometimes a system needs to download multiple files at once, and downloading them one by one is cumbersome. The best solution is to package all files into a compressed archive and download that archive, allowing all required files to be obtained in a single operation.
The following code defines a utility class called CompressUtil that offers several methods for handling file compression and download operations.
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: Compression utility class
*/
public class CompressUtil {
private static final Logger logger = LoggerFactory.getLogger(CompressUtil.class);
/**
* Pack files into a zip and create the file
* @param sourceFilePath
* @param zipFilePath
* @throws IOException
*/
public static void createLocalCompressFile(String sourceFilePath, String zipFilePath) throws IOException {
createLocalCompressFile(sourceFilePath, zipFilePath, null);
}
/**
* Pack files into a zip and create the file
* @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);
}
}
/**
* Get compression file stream
* @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);
}
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;
}
}
private static void doCompressFile(File sourceFile, ZipOutputStream zipOutputStream, String zipFilePath) throws IOException {
// Skip hidden files
if (sourceFile.isHidden()) {
return;
}
if (sourceFile.isDirectory()) {
handDirectory(sourceFile, zipOutputStream, zipFilePath);
} else {
try (FileInputStream fileInputStream = new FileInputStream(sourceFile)) {
String fileName = zipFilePath + sourceFile.getName();
addCompressFile(fileInputStream, fileName, zipOutputStream);
}
}
}
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);
}
}
public static OutputStream compressFile(List
documentList, OutputStream outputStream) {
Map
> documentMap = new HashMap<>();
documentMap.put("", documentList);
return compressFile(documentMap, outputStream);
}
public static OutputStream compressFile(Map
> documentMap, OutputStream outputStream) {
CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream, new CRC32());
ZipOutputStream zipOutputStream = new ZipOutputStream(checkedOutputStream);
try {
for (Map.Entry
> documentListEntry : documentMap.entrySet()) {
String dirName = documentMap.size() > 1 ? documentListEntry.getKey() : "";
Map
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;
}
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();
} catch (Exception e) {
logger.info("addFileToZip exception:", e);
throw new RuntimeException(e);
}
}
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();
}
}
public static void httpDownloadCompressFile(String sourceFilePath, HttpServletResponse response) throws IOException {
httpDownloadCompressFile(sourceFilePath, response, null);
}
/**
* Check if a file name already exists; if it does, append "(1)", "(2)", etc.
* @param filename File name
* @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;
}
}Test compression and generate a local file:
public static void main(String[] args) throws Exception {
// Create a zip file locally
CompressUtil.createLocalCompressFile("D:\\书籍\\电子书\\医书", "D:\\test");
}The result of compressing and generating the file locally can be verified (image omitted).
Compress the file and download it via an HTTP request:
@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);
}
}The result of downloading the compressed file through HTTP can be verified (image omitted).
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.