Sort a directory listing (based on the last modified timestamp)Tag(s): IO


This HowTo sorts a directory listing in ascending or descending order (based on the last modified timestamp).
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

public class FileUtils{

  public static void main(String args[]) throws Exception {
    File files[] = FileUtils.dirListByAscendingDate
         (new File("C:/Applications/folder"));
    for (File file : files) {
      System.out.println(file.getName() + " " 
         + new Date(file.lastModified()));
    }
    System.out.println("*********");
    files = FileUtils.dirListByDescendingDate
      (new File("C:/Applications/folder"));
    for (File file : files) {
      System.out.println(file.getName() + " " 
         + new Date(file.lastModified()));
    }

  }
  
  @SuppressWarnings("unchecked")
  public static File[] dirListByAscendingDate(File folder) {
    if (!folder.isDirectory()) {
      return null;
    }
    File files[] = folder.listFiles();
    Arrays.sort( files, new Comparator()
    {
      public int compare(final Object o1, final Object o2) {
        return new Long(((File)o1).lastModified()).compareTo
             (new Long(((File) o2).lastModified()));
      }
    }); 
    return files;
  }  
  
  @SuppressWarnings("unchecked")
  public static File[] dirListByDescendingDate(File folder) {
    if (!folder.isDirectory()) {
      return null;
    }
    File files[] = folder.listFiles();
    Arrays.sort( files, new Comparator()
    {
      public int compare(final Object o1, final Object o2) {
        return new Long(((File)o2).lastModified()).compareTo
             (new Long(((File) o1).lastModified()));
      }
    }); 
    return files;
  }  
}
Take a look at this HowTo to filter by a date interval.
Take a look at this HowTo to sort the filenames based on the extension.

blog comments powered by Disqus