我想得到一个目录中的文件列表,但我想对它进行排序,以使最旧的文件排在第一位.我的解决方案是调用File.列出文件,然后根据文件 Select 列表.最后修改了,但我想知道是否有更好的方法.

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

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

推荐答案

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相关问答推荐

无法在Java中使用Curve secp 256 k1验证JWT

如果它最终将被转换为int类型,为什么我们在Java中需要较小的integer类型?

使用JdkClientHttpRequestFactory通过Spring RestClient和Wiemock读取时达到EOF

使用传递的参数构造异常的Mockito-doThrow(或thenThrow)

我无法获取我的Java Spring应用程序的Logback跟踪日志(log)输出

OpenGL ES 3.0-纹理黑色

JDK 21-为什么线程局部随机S nextInt不直接用Super.nextInt实现?

在学习Spring时,通过构造函数参数0表达了不满意的依赖关系

垃圾收集时间长,会丢弃网络连接,但不会在Kubernetes中反弹Pod

如何在透视表中添加对计数列的筛选?

从映射列表中检索所有键

我可以在@Cacheable中使用枚举吗

从泛型枚举创建EnumMap

何时调用密封层次 struct 的switch 中的默认情况

如何在Record Java中使用isRecord()和RecordComponent[]?

在Java中将对象&转换为&q;HashMap(&Q)

在Spring Boot中使用咖啡因进行缓存

如何使用jOOQ在PostgreSQL中从枚举类型生成Java枚举

升级版本后出现非法访问错误

错误:JOIN/ON的参数必须是boolean类型,而不是bigint类型.Java Spring启动应用程序