Best way to list files in Java, sorted by Date Mod

2018-12-31 17:35发布

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());
    } });

16条回答
若你有天会懂
2楼-- · 2018-12-31 18:05

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.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 18:07

Elegant solution since Java 8:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Or, if you want it in descending order, just reverse it:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
查看更多
临风纵饮
4楼-- · 2018-12-31 18:07

In Java 8:

Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));

查看更多
看风景的人
5楼-- · 2018-12-31 18:08

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-

File downloadDir = new File("mypath");    
File[] list = downloadDir.listFiles();
    for (int i = list.length-1; i >=0 ; i--) {
        //use list.getName to get the name of the file
    }

Thanks

查看更多
余生请多指教
6楼-- · 2018-12-31 18:10

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().

查看更多
皆成旧梦
7楼-- · 2018-12-31 18:10

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:

    Collection<File> files = ...
    final Map<File, Long> staticLastModifiedTimes = new HashMap<File,Long>();
    for(final File f : files) {
        staticLastModifiedTimes.put(f, f.lastModified());
    }
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File f1, final File f2) {
            return staticLastModifiedTimes.get(f1).compareTo(staticLastModifiedTimes.get(f2));
        }
    });
查看更多
登录 后发表回答