如何在java中按日期对目录中的文件进行排序? [英] How to sort files from a directory by date in java?
问题描述
我有一个从位于目录中的文件中读取内容的方法。但由于功能原因,有必要从最旧的文件开始(由属性lastmodified指示)并以最新文件结束。
I have a method which reads the content from files located in a directory. But for functional reasons it is necessary to start with the oldest file (indicated by the property lastmodified) and end with the newest file.
这是我打开的代码和读取文件:
This is the code how I open and read the files:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches("access_log.*");
}
};
File folder = new File("/home/myfiles");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
String sFileName = listOfFiles[i].getName();
File accessLogFile = new File(aLog.getPath(), sFileName);
long time=accessLogFile.lastModified();
// do something with the file
}
有人解决方法如何我可以按日期快速对文件列表进行排序吗?
Has anybody a solution how I can quickly sort my list of files by date?
推荐答案
编辑:
在java8中:
Arrays.sort(文件,(a,b) - > Long.compare(a。 lastModified(),b.lastModified()));
链接
我发现了一些有趣的代码,非常接近你所需要的,看看它(只是快速运行Comparator的实现):
I found some interesting code,very close to what you need, have a look at it(Just a quick on the run implementation of Comparator):
File f = new File("/home/myfiles");
File [] files = f.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
此外,你可以查看这篇文章,看看这家伙是如何解决这个问题的:列出Java文件的最佳方法,按修改日期排序?
Also you can have a look at this post, see how the guy solved the problem: Best way to list files in Java, sorted by Date Modified?
这篇关于如何在java中按日期对目录中的文件进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!