一个小工具,使用JSP实现下载最近一天日志

本文介绍了一个使用JSP和Java实现的日志文件下载工具。该工具能够将指定目录下的最新日志文件压缩为ZIP格式,并提供下载链接。具体实现了文件筛选、压缩及HTTP响应头设置等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做了一个小工具,一个JSP页面,放在Tomcat下,用来下载最新的日志文件。其中文件会被打包成zip格式。

<%@page import="java.io.*"%>
<%@page import="java.util.zip.*"%>
<%

String logDirFullPath ="D:\\temp\\cmd\\scripts";
String zipFileFullPath="D:\\temp\\cmd\\logs.zip";

File dirFile=new File(logDirFullPath);
File zipFile=new File(zipFileFullPath);

if(zipFile.exists()){
    zipFile.delete();
}

ZipOutputStream zipOutStream=new ZipOutputStream(new FileOutputStream(zipFileFullPath));
String base="";
//zipOutStream.putNextEntry(new ZipEntry(base));
for(File f:dirFile.listFiles()){
    if(f.isFile()&&((System.currentTimeMillis()-f.lastModified())<(24*60*60*1000))){
        ZipEntry entry=new ZipEntry(base+f.getName());
        entry.setTime(f.lastModified());
        zipOutStream.putNextEntry(entry);
        FileInputStream fis=new FileInputStream(f);
        byte[] buffer=new byte[1024000];
        int b;
        while((b=fis.read(buffer))!=-1){
        zipOutStream.write(buffer, 0, b);
        }
        fis.close();
    }
}
zipOutStream.close();

////////////////////////////////////////////////////////////////////////////////////////

File file=new File(zipFileFullPath);
byte[] data=new byte[(int)file.length()];
FileInputStream fis=null;
try{
    fis=new FileInputStream(file);
    int r=fis.read(data);
}catch(Exception e){
    e.printStackTrace();
}finally{
    if(fis!=null){
        try{
            fis.close();
        }catch(Exception ioe){
            ioe.printStackTrace();
        }
    }
}

response.setHeader("Content-Disposition", "attachment; filename=\""+file.getName()+"\"");  
response.addHeader("Content-Length", "" + data.length);  
response.setContentType("application/octet-stream;charset=UTF-8");

OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
outputStream.write(data);  
outputStream.flush();  
outputStream.close();
response.flushBuffer();

%>

 

转载于:https://my.oschina.net/shawnplaying/blog/736025

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值