工具类FileUtil
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class FileUtil {
private FileUtil(){}
private static final int BUFFER_SIZE = 2 * 1024;
@SneakyThrows
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) {
long start = System.currentTimeMillis();
try(ZipOutputStream zos =new ZipOutputStream(out)){
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
log.info("压缩完成,耗时: {} ms", end - start);
}
}
@SneakyThrows
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
zos.putNextEntry(new ZipEntry(name));
int len;
try(FileInputStream in = new FileInputStream(sourceFile)){
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
}
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
if (KeepDirStructure) {
zos.putNextEntry(new ZipEntry(name + "/"));
zos.closeEntry();
}
} else {
for (File file : listFiles) {
if (KeepDirStructure) {
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
}
Service代码
@SneakyThrows
private void uoloadZip(String folderPath){
String zipPath=folderPath+".zip";
FileUtil.toZip(folderPath, Files.newOutputStream(Paths.get(zipPath)),true);
HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
response.setContentType("applicaation/octet-stream");
response.addHeader("Content-disposition", "attachment;filename=" +UUID.randomUUID());
IOUtils.copy(new FileInputStream(zipPath),response.getOutputStream());
}