Contact at mumbai.academics@gmail.com or 8097636691
Responsive Ads Here

Saturday, 30 June 2018

Commons IO - LastModifiedFileComparator

Commons IO - LastModifiedFileComparator


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 −
public class LastModifiedFileComparator
   extends Object implements Serializable

Example of LastModifiedFileComparator Class

Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try {
         usingLastModifiedFileComparator();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }

   public static void usingLastModifiedFileComparator() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      LastModifiedFileComparator comparator = new LastModifiedFileComparator();

      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));

      System.out.println("Sorted By Last Modified date: ");
      for(File file:sortedFiles) {      
         System.out.println(file.getName() + ", Modified on: " + new Date(file.lastModified()));
      }
   }
}

Output

It will print the following result.
Sorted By Last Modified date: 
.project, Modified on: Thu Oct 12 19:06:45 IST 2017
.classpath, Modified on: Mon Nov 20 13:09:55 IST 2017
input.txt, Modified on: Mon Nov 20 19:27:55 IST 2017

No comments:

Post a Comment