在web application中,有时需要查看log4j产生的log文本文件,在网络速度有限时,在下载log文件前将其读入内存并转化成压缩内容直接下载,不但速度快,而且不用在服务器上硬盘产生压缩文件,具体代码如下jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.io.*"%><%@page import="java.util.zip.*"%>
<%@page import="java.util.*"%>
<%
String filename = request.getParameter("filename");
String selfPath = this.getServletContext().getRealPath("/");
selfPath=selfPath+File.separator+"logs";
String filepath = selfPath+File.separator+filename;
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(filepath);
int filelength =inputStream.available() ;
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream( );
InputStream is = new FileInputStream(filepath);
ZipEntry entry = new ZipEntry(filename);
ZipOutputStream zos = new ZipOutputStream( byteOutputStream );
zos.putNextEntry(entry);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read( buffer)) != -1) {
zos.write(buffer, 0, i);
}
inputStream.close();
zos.close();
String fileminitype="application/x-download";
response.setContentType(fileminitype);
response.setHeader("Content-Disposition", "attachment; filename=" + filename+".zip");
response.setContentLength( byteOutputStream.size() );
outputStream.write( byteOutputStream.toByteArray() );
byteOutputStream.close();
outputStream.close();
%>