在 Java 中列出文件的最佳方法,按修改日期排序? [英] Best way to list files in Java, sorted by Date Modified?

查看:36
本文介绍了在 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() 并且文档指出这不能保证返回文件的顺序.因此,您需要编写一个 Comparator 使用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().

这篇关于在 Java 中列出文件的最佳方法,按修改日期排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆