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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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 with Thumbnails

3 Responses to “Java: Sort Files By Date Modified In Descending Order”

  1. 1
    jar Says:

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

  2. 2
    vw30Ellie Says:

    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.

  3. 3
    Rubi Archangel Says:

    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.

Leave a Reply

Spam protection by WP Captcha-Free