Compare the last modified dates of two files/directory. LastModifiedFileComparator can be used to sort lists or arrays of files/directories using their last modified dates.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.LastModifiedFileComparator Class −

  1. public class LastModifiedFileComparator
  2. extends Object implements Serializable

Example of LastModifiedFileComparator Class

Here is the input file we need to parse −

  1. Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

  1. import java.io.File;
  2. import java.io.FileFilter;
  3. import java.io.IOException;
  4. import java.util.Date;
  5.  
  6. import org.apache.commons.io.comparator.LastModifiedFileComparator;
  7. import org.apache.commons.io.filefilter.FileFileFilter;
  8.  
  9. public class IOTester {
  10. public static void main(String[] args) {
  11. try {
  12. usingLastModifiedFileComparator();
  13. } catch(IOException e) {
  14. System.out.println(e.getMessage());
  15. }
  16. }
  17.  
  18. public static void usingLastModifiedFileComparator() throws IOException {
  19. //get the current directory
  20. File currentDirectory = new File(".");
  21.  
  22. LastModifiedFileComparator comparator = new LastModifiedFileComparator();
  23.  
  24. File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
  25.  
  26. System.out.println("Sorted By Last Modified date: ");
  27. for(File file:sortedFiles) {
  28. System.out.println(file.getName() + ", Modified on: " + new Date(file.lastModified()));
  29. }
  30. }
  31. }

Output

It will print the following result.

  1. Sorted By Last Modified date:
  2. .project, Modified on: Thu Oct 12 19:06:45 IST 2017
  3. .classpath, Modified on: Mon Nov 20 13:09:55 IST 2017
  4. input.txt, Modified on: Mon Nov 20 19:27:55 IST 2017