java保留一定时间段内的日志


import com.odss.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class updateLogFiles {
    static String path="E:/IdeaProjects/ODSS/logs/error.log";//路径
    public static void main(String[] args) {
        File fileText=new File(path);
        if(fileText.canExecute())
            setText();
    }
    private static void setText() {//修改
        //获取文件路径上的文件
        File fileText=new File("logs/error.log");

        //判断文件是否存在
        if(!fileText.canExecute()){
            return;
        }

        //设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();

        //设置过期时间,此处设置时间超过一天的
        Long now3 = now.getTime()-1*24*60*60*1000;
        String target = simpleDateFormat.format(new Date(now3));
        BufferedReader br = null;
        PrintWriter pw = null;
        StringBuffer buff = new StringBuffer();//临时容器!
        String line = System.getProperty("line.separator");//平台换行!
        try {
            br = new BufferedReader(new FileReader(fileText));
            for(String str = br.readLine();str != null;str = br.readLine()) {
                //如果该行为空,则跳过
                if(str.equals("")||str.equals(null)){
                    continue;
                }
                //获取日志中的时间
                Date logDate = simpleDateFormat.parse(str.substring(0, target.length()));
                Date delDate = simpleDateFormat.parse(target);

                //若记录的日志时间大于指定删除的时间,则保留该行数据
                if(logDate.getTime() > delDate.getTime()) {
                    buff.append(str + line);
                }
            }

            //将保留的内容写入文件
            pw=new PrintWriter(new FileWriter(fileText),true);
            pw.println(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(pw!=null)
                pw.close();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。