获取按上次修改排序的目录中的文件? [英] Get files in a directory sorted by last modified?
本文介绍了获取按上次修改排序的目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 7中使用新的I / O API,是否有一种简单的方法可以按上次修改日期列出目录的内容?基本上我只需要获取最长时间没有修改的文件(按上次修改升序排序,取第一个文件名)。
In Java 7 with the new I/O APIs, is there an easy way to list a directory's content by last modified date? Basically I only need to get the file the wasn't modified for the longest time (sort by last modified ascending, take first filename).
推荐答案
没有真正的简单方法,但有可能:
There's no real "easy way" to do it, but it is possible:
List<Path> files = new ArrayList<>();
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for(Path p : stream) {
files.add(p);
}
}
Collections.sort(files, new Comparator<Path>() {
public int compare(Path o1, Path o2) {
try {
return Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2));
} catch (IOException e) {
// handle exception
}
}
});
这将对最后修改过的文件进行排序。 DirectoryStream
s不会遍历子目录。
This will sort the files soonest modified files last. DirectoryStream
s do not iterate through subdirectories.
这篇关于获取按上次修改排序的目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文