Total Pageviews

2017/07/11

Utilize AgeFileFilter to filter either newer files or files equal to or older

Scenario
I have an requirement to read a specific directory (including subdirectories) to find five days before log files and delete them.
How to do it?

How-To
Add commons-io to your maven dependency:
1
2
3
4
5
    <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.5</version>
    </dependency>


Here has code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    /**
     * 找出某個日期以前的檔案.
     * 
     * @param directory 找出某個目錄下的檔案
     * @param days 找出數天前 (如 -20)
     * @param includeSubdir 是否包含子目錄 (true / false)
     * @return List of File
     */
    public static List<File> getFilesBeforeXDays(File directory, int days, Boolean includeSubdir) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, days);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        Date date = cal.getTime();

        IOFileFilter ageFileFilter = FileFilterUtils.ageFileFilter(date);
        IOFileFilter subDirFilter = includeSubdir ? FileFilterUtils.trueFileFilter()
                : FileFilterUtils.falseFileFilter();

        Collection<File> fileCollection = org.apache.commons.io.FileUtils.listFiles(directory, ageFileFilter, subDirFilter);
        if(CollectionUtils.isEmpty(fileCollection)){
            log.info("Cannot find any log files before " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(date));
        } else{
            log.info("Find " + fileCollection.size() + " log file(s).");
        }
        
        return new ArrayList<File>(fileCollection);
    }




Reference
[1] https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/filefilter/AgeFileFilter.html    

No comments: