删除java中的日志文件

时间:2014-04-29 17:39:39

标签: java file logging delete-file

我想创建一个方法,该方法应递归检查XYZ.xyz()目录下的所有目录,查找匹配pattern" job_log_YYYYMMDDHHSS.txt"的文件。如果文件中指示的日期相对于当前日期超过30天,请删除该文件。

public class logCleanup extends XyzJob implements Job {

private static final int daysToRetain = 30;

private void cleanJobLogs() throws Exception {
    String LogDir = System.getProperty("user.dir") + "\\txt";

    Calendar c = Calendar.getInstance();
    if (c.get(Calendar.HOUR_OF_DAY) == 0 && c.get(Calendar.MINUTE) < 6) {
        int filesDeletedCount = 0;
        File dir = new File(LogDir);
        String[] logFileNames = dir.list();
        Calendar fileDate = Calendar.getInstance();
        Calendar cutoffDate = Calendar.getInstance();
        cutoffDate.add(Calendar.DAY_OF_MONTH, -daysToRetain);
        cutoffDate.set(Calendar.HOUR_OF_DAY, 0);
        cutoffDate.set(Calendar.MINUTE, 0);
        cutoffDate.set(Calendar.SECOND, 0);

        for (int i = 0; i < logFileNames.length; i++) {
            String fileName = logFileNames[i];
            String[] fileNameParts = fileName.split("\\.");
            if (fileNameParts.length == 3) // match log file name pattern
            {
                try {
                    // parsing file's date
                    SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHSS");
                    fileDate.setTime(sdf.parse(fileNameParts[1]));

                    // delete files older than then cutoff date
                    if (fileDate.before(cutoffDate)) {
                        File deleteFile = new File(LogDir + "\\" + fileName);
                        if (!deleteFile.delete()) {
                            log("        Unable to Delete File: " + LogDir + "\\" + fileName);
                        } else {
                            filesDeletedCount++;
                        }
                    }
                } catch (Exception e) {
                    // parse date out of filename or delete file
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

final File folder = new File("yourdirectory");
FilenameFilter fileFilter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      return name.toLowerCase().endsWith("yourpattern");
    }
};

for (final File fileEntry : folder.listFiles(fileFilter)) {
     if (System.currentTimeMillis() - fileEntry.lastModified() > 2592000000L)
        fileEntry.delete();
}