
The LastModifiedFileComparator.LASTMODIFIED_COMPARATOR and LastModifiedFileComparator.
LASTMODIFIED_REVERSE Comparator singleton instances in the Apache Commons IO library can be used to sort arrays or collections of files according to their last-modified dates.

Please follow below steps:
- You need to add
commons-io-2.6.jarfile into your Java Project’s class path. - If you are on Mac OS X then you need to create a temp folder under Downloads, i.e. /Users/<username>/Downloads/CrunchifyTest
- Create two files Crunchify_Test1.txt and Crunchify_Test2.txt
If you have maven project then add below pom.xml maven dependency.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Here is a complete Java Program:
package com.crunchify.tutorials;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
/**
* @author Crunchify.com
*
*/
public class CrunchifySortFileLastModifiedTime {
public static void main(String[] args) {
File dir = new File("/Users/<username>/Downloads/CrunchifyTest");
File[] files = dir.listFiles();
System.out.println("Sort files in ascending order base on last modification date");
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File: %s - " + new Date(file.lastModified()) + "\n", file.getName());
}
System.out.println("\nSort files in descending order base on last modification date");
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File: %s - " + new Date(file.lastModified()) + "\n", file.getName());
}
}
}
Other must read:
- Java: Create a Timer Object for Future Execution in a Background Thread
- How to Start/Spawn New Thread in Background in Java
Output:
Here is an Eclipse Console result. Just run it as a Java Application.
Sort files in ascending order base on last modification date File: Crunchify_Test1.txt - Fri Jul 05 10:24:08 PDT 2013 File: Crunchify_Test2.txt - Fri Jul 05 10:25:03 PDT 2013 Sort files in descending order base on last modification date File: Crunchify_Test2.txt - Fri Jul 05 10:25:03 PDT 2013 File: Crunchify_Test1.txt - Fri Jul 05 10:24:08 PDT 2013
Let me know if you find better ways to sort list of files via comment below.
