利用JDK自带的zip相关类,在util目录下。
1、生成zip文件
public String createLog() throws IOException {
String zipFileName = null;
String logFolderPath = PathConst.LOG_PATH;
File[] logFiles = taskLogFolder.listFiles();
zipFileName = "log.zip";
String zipFileNamePath = logFolderPath + "/" + zipFileName;
File zipFile = new File(zipFileNamePath);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
FileInputStream fileInputStream = null;
byte[] buf = new byte[1024];
int len = 0;
if (logFiles != null && logFiles.length > 0) {
for (File logFile : logFiles) {
String fileName = logFile.getName();
if (!fileName.equals(zipFileName)) {
fileInputStream = new FileInputStream(logFile);
//放入压缩包
zipOutputStream.putNextEntry(new ZipEntry(fileName));
//读取文件
while ((len = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, len);
}
//关闭
zipOutputStream.closeEntry();
fileInputStream.close();
}
}
}
zipOutputStream.close();
return zipFileName;
}
2、下载zip文件
public void downloadLog(String zipFileName, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
String zipFilePath = PathConst.LOG_PATH;
File file = new File(zipFilePath, zipFileName);
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
OutputStream outStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFileName.getBytes("UTF-8"), "ISO-8859-1"));
outStream.write(buffer);
outStream.flush();
outStream.close();
}
Content-type
内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件。
文件扩展名与 Content-type 的对应关系,参见 http://tool.oschina.net/commons
Content-Disposition
Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 IE 浏览器接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。Content-Disposition 就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。
本文介绍了一种使用Java标准库中的zip相关类来压缩和下载日志文件的方法。通过创建一个zip文件将多个日志文件打包,并提供了一个下载功能,允许用户以zip格式下载这些日志。

1366

被折叠的 条评论
为什么被折叠?



