import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileZipUtil {
private static Logger log = LoggerFactory.getLogger(FileZipUtil.class);
/**
* 浏览器下载zip文件(下载本项目所有日志文件)
* @param response
*/
public static void downLoadLogToZip(HttpServletResponse response) {
log.info("开始下载日志");
// 设置响应流信息
response.setContentType("application/x-zip-compressed");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Disposition", "attachment;filename=logs.zip");
response.setDateHeader("Expires", 0);
//取出日志文件所在文件夹
File inputFile = new File("logs");
log.info("将要下载日志所在路径==>" + inputFile.getAbsolutePath());
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(response.getOutputStream());
compress(zipOutputStream, inputFile, null);
} catch (IOException e) {
e.printStackTrace();
log.error("日志下载异常");
} finally {
try {
zipOutputStream.flush();
zipOutputStream.close();
log.info("日志下载成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 递归压缩
* @param out ZipOutputStream
* @param input 要压缩的文件
* @param name 可以写为null保持默认
* @throws IOException
*/
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();
//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入
if (flist.length == 0) {
out.putNextEntry(new ZipEntry(name + "/"));
} else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
for (int i = 0; i < flist.length; i++) {
compress(out, flist[i], name + "/" + flist[i].getName());
}
}
} else {//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(name));
FileInputStream fos = new FileInputStream(input);
BufferedInputStream bis = new BufferedInputStream(fos);
int len;
//将源文件写入到zip文件中
byte[] buf = new byte[1024];
while ((len = bis.read(buf)) != -1) {
out.write(buf, 0, len);
}
bis.close();
fos.close();
}
}
}
压缩文件(日志,多文件)下载工具类
最新推荐文章于 2024-07-12 16:03:08 发布