Java: Sort Files By Date Modified In Descending Order

There came a point that I had to display a list of log files in a certain directory for my boss to view. The important thing with the list display is that the files should be sorted in descending order. From top would be the latest while the oldest would be down at the bottom. Java can do sorting through the Comparator Class. And luckily, I found a post in a forum that saved me the time and trouble to make a custom method for it. The code looks like this.

public static void sortFilesDesc(File[] files) {
  Arrays.sort(files, new Comparator() {
    public int compare(Object o1, Object o2) {
      if ((File)o1).lastModified().compareTo((File)o2).lastModified()) {
        return -1;
      } else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
        return +1;
      } else {
        return 0;
      }
    }
  });
}

Take note that this method includes sorting directories together with the files as one.

Donations appreciated. Every little $ helps. Or click Google +1.

Related Posts Plugin for WordPress, Blogger...
  1. 4 Responses to “Java: Sort Files By Date Modified In Descending Order”

  2. Arrays.sort(fileList, new Comparator() {
    public int compare(File f1, File f2) {
    return Long.valueOf(f1.lastModified()).compareTo(
    f2.lastModified());
    }
    });

    By jar on Jun 3, 2009

  3. From time to time different people try to search for the writing associated with writing essays. And I can propose to utilize the help of the writing service. At the same time, it’s available to use some stuff from the this topic theme.

    By vw30Ellie on Jan 1, 2010

  4. Wonderful site, where did you come up with the knowledge in this piece of writing? Im happy I found it though, ill be checking back soon to see what other articles you have.

    By Rubi Archangel on Apr 8, 2010

  5. thanks! it helped me a lot to compare dates

    By franjo on Dec 27, 2011

Post a Comment