在项目开发中有选中多个文件打包下载和选中文件夹下载文件夹内所有文件的功能需求。
用到的压缩工具类如下:
public class Compress {
//压缩包暂存位置
private static String TEMP_PATH = "D:\\YUN\\DISK\\zipTmp";
private static Boolean moreFile = Boolean.valueOf(false);
private static Boolean isFirst = Boolean.valueOf(true);
//压缩包名字
private static String zipName = "";
public Compress(String zipName) {
this.moreFile = Boolean.valueOf(true);
this.isFirst = Boolean.valueOf(true);
this.zipName = zipName;
this.TEMP_PATH = "D:\\YUN\\DISK\\zipTmp";
}
public String compress(List<File> fileList) {
File zipFile = new File(this.TEMP_PATH + "/"+ zipName + ".zip");
try {
//压缩输出流
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
//遍历文件列表
for (File file : fileList)
compress(out, file, null);
//冲刷缓冲区
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return zipFile.getPath();
}
public static void compress(ZipOutputStream out, File input, String name) throws IOException {
if (name == null)
name = input.getName();
//如果是文件夹
if (input.isDirectory()) {
//获取子文件列表
File[] flist = input.listFiles();
if (flist.length == 0) {
//如果是空文件夹 压缩一个空文件夹进压缩包
out.putNextEntry(new ZipEntry(name + "/"));
}
//递归调用
else {
for (int i = 0; i < flist.length; i++)
compress(out, flist[i], name + "/" + flist[i].getName());
}
}
//如果是文件
else {
FileInputStream fos = new FileInputStream(input);
byte[] data = new byte[(int)input.length()];
fos.read(data);
out.putNextEntry(new ZipEntry(name));
out.write(data);
fos.close();
out.closeEntry();
}
}
}