java 获得文件夹修改日期,如何在java中获取目录的最后修改日期和时间

在Java中,可以通过File对象的lastModified()方法获取文件的最后修改时间。然而,在Windows系统下,只有被修改的文件时间戳会更新,而非整个文件夹。为了解决这个问题,可以遍历文件夹中的所有文件,找出最后修改的文件时间。提供的代码实现了一个方法,它返回目录中所有文件中最后修改的那个文件的时间,如果目录为空,则返回目录本身的修改时间。
摘要由CSDN通过智能技术生成

See, the problem is that in Java, we can get lastmodified date by filename.lastModified(). But in Windows, what is happening is that whenever a file is modifed, only that file's date and time are getting modified, not the whole folder's. So I want to know when was the last time even one single file was modified in that folder, using Java?

解决方案

Find the latest (largest) lastModified() in the directory's files, or if there are none use the directory's itself:

public static Date getLastModified(File directory) {

File[] files = directory.listFiles();

if (files.length == 0) return new Date(directory.lastModified());

Arrays.sort(files, new Comparator() {

public int compare(File o1, File o2) {

return new Long(o2.lastModified()).compareTo(o1.lastModified()); //latest 1st

}});

return new Date(files[0].lastModified());

}

FYI this code has been tested (and it works).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值