前言
最近做个小工具需要提供一个将 resources 资源文件夹下某个目录(放了一些模板集合)打包下载功能
尝试
祖传的 zip 文件夹功能代码先送上:
public void zip(ZipOutputStream out, File sourceFile, String base) throws Exception {
//如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹)
File[] fileList = sourceFile.listFiles();
if (fileList.length == 0) {
//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
System.out.println(base + "/");
out.putNextEntry(new ZipEntry(base + "/"));
} else {
//如果文件夹不为空,则递归调用zip,文件夹中的每一个文件(或文件夹)进行压缩
for (File file : fileList) {
zip(out, file, base + "/" + file.getName());
}
}
} else {
//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(base));
<