Java Example of org.apache.commons.io.comparator

Q

Where can I find an example Java code that uses the org.apache.commons.io.comparator package?

✍: FYIcenter.com

A

org.apache.commons.io.comparator package provides various java.util.Comparator implementations for java.io.File. These comparators can be used to sort lists and arrays of files, for example.

Prasad Saya provided a good Java example that uses the org.apache.commons.io.comparator package at javacodegeeks.com Website.

import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Date;
import java.text.SimpleDateFormat;

public class LastModFileComparatorExample {
   public static void main(String [] args) {
      LastModifiedFileComparator comparator = new LastModifiedFileComparator();
      System.out.println("### Input files ###");
      File dir = new File("C:\\local\\commons-io-2.5\\");
      File [] files = dir.listFiles();
      printArrayContents(files);
      System.out.println("### Array sorted ###");
      files = comparator.sort(files);
      printArrayContents(files);
   }

   private static void printArrayContents(File [] files) {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy MMM dd HH:mm");
      for (File file : files) {
         Date date = new Date(file.lastModified());
         System.out.println(formatter.format(date) + "   " + file.getName());
      }
      System.out.println("");
   }
}

You can compile and run the above example in a command window as shown below:

C:\fyicenter>javac -cp C:\local\commons-io-2.5\commons-io-2.5.jar 
   LastModFileComparatorExample.java

C:\fyicenter>java -cp .;C:\local\commons-io-2.5\commons-io-2.5.jar 
   LastModFileComparatorExample
   
### Input files ###
2016 Apr 15 17:37   commons-io-2.5-javadoc.jar
2016 Apr 15 17:37   commons-io-2.5.jar
2016 Nov 12 22:13   docs
2016 Apr 14 10:18   LICENSE.txt
2016 Apr 14 10:18   NOTICE.txt
2016 Apr 14 10:18   RELEASE-NOTES.txt

### Array sorted ###
2016 Apr 14 10:18   LICENSE.txt
2016 Apr 14 10:18   NOTICE.txt
2016 Apr 14 10:18   RELEASE-NOTES.txt
2016 Apr 15 17:37   commons-io-2.5.jar
2016 Apr 15 17:37   commons-io-2.5-javadoc.jar
2016 Nov 12 22:13   docs

 

Using commons-io.jar in Java Code

⇒⇒FAQ for Apache commons-io.jar

2017-04-28, 442👍, 0💬