在Java中列出文件的最佳方法是按日期修改排序?

问题描述:

我想获取一个目录中的文件列表,但是我想对它进行排序,以便最旧的文件是第一个。我的解决方案是调用File.listFiles,只是根据File.lastModified打开列表,但是我想知道是否有更好的方法。

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.

编辑:我当前的解决方案根据建议,使用匿名比较器:

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


我认为您的解决方案是唯一合理的方式。获取文件列表的唯一方法是使用 File.listFiles(),并且文档说明,这不保证返回文件的顺序。因此,您需要编写一个使用的比较器 File.lastModified()并将其与文件数组一起传递给 Arrays.sort()

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