I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.
Edit: My current solution, as suggested, is to use an anonymous Comparator:
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
} });
You might also look at apache commons IO, it has a built in last modified comparator and many other nice utilities for working with files.
Elegant solution since Java 8:
Or, if you want it in descending order, just reverse it:
In Java 8:
Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));
I came to this post when i was searching for the same issue but in
android
. I don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.Below code may be helpful to someone-
Thanks
I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().
If the files that you are sorting are being modified / updated while the sort is being performed you will be violating the transitivity requirement of the comparator's general contract. To avoid this potential bug, you'll want to build up a static lookup table of last modified values to use in the comparator for each file, something like the following: