Total Pageviews

2014/05/23

How do I sort an array of files according to their last modified dates?

Apache commons IO provide LastModifiedFileComparator to do file sorting based on its last modified date/time.
It provide two instance:
1. LASTMODIFIED_COMPARATOR: Last modified comparator instance
2. LASTMODIFIED_REVERSE: Reverse last modified comparator instance

Example
1. Read files from old to new
   /**  
    * The main method.  
    *   
    * @param args  
    *      the arguments  
    */  
   public static void main(String args[]) {  
     Collection files =   
       FileUtils.listFiles(new File(FmsBatchConfig.INPUT_FOLDER_PATH), // assign file path  
                 FileFilterUtils.prefixFileFilter("COP0407"), // assign file name  
                 FalseFileFilter.FALSE);// include subdirectories  
     File[] fileArr = files.toArray(new File[files.size()]);  
     Arrays.sort(fileArr, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);//from old to new  
     // print file name  
     for (File file : fileArr) {  
       System.out.println(file.getName()+"["+new Date(file.lastModified())+"]");  
     }  
   }  

The console will print
 COP0407_01_1030501.txt[Thu May 08 16:45:01 CST 2014]  
 COP0407_01_1030502.txt[Fri May 23 10:31:45 CST 2014]  

2. Read files from new to old
   /**  
    * The main method.  
    *   
    * @param args  
    *      the arguments  
    */  
   public static void main(String args[]) {  
     Collection files =   
       FileUtils.listFiles(new File(FmsBatchConfig.INPUT_FOLDER_PATH), // assign file path  
                 FileFilterUtils.prefixFileFilter("COP0407"), // assign file name  
                 FalseFileFilter.FALSE);// include subdirectories  
     File[] fileArr = files.toArray(new File[files.size()]);  
     Arrays.sort(fileArr, LastModifiedFileComparator.LASTMODIFIED_REVERSE);//from new to old  
     // print file name  
     for (File file : fileArr) {  
       System.out.println(file.getName()+"["+new Date(file.lastModified())+"]");  
     }  
   }  

The console will print
 COP0407_01_1030502.txt[Fri May 23 10:31:45 CST 2014]  
 COP0407_01_1030501.txt[Thu May 08 16:45:01 CST 2014]  

Reference
[1] http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/comparator/LastModifiedFileComparator.html

No comments: