This question already has an answer here:
這個問題在這里已有答案:
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.
我有一個方法從位於目錄中的文件中讀取內容。但由於功能原因,有必要從最舊的文件開始(由屬性lastmodified指示)並以最新文件結束。
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?
有沒有人可以解決我如何按日期快速排序我的文件列表?
3 个解决方案
#1
37
Edit: In java8:
編輯:在java8中:
Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified())); link
Arrays.sort(files,(a,b) - > Long.compare(a.lastModified(),b.lastModified()));鏈接
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):
我找到了一些有趣的代碼,非常接近你需要的東西,看看它(只是快速運行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;
}
}
});
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列出文件的最佳方法,按修改日期排序?
#2
3
Your best option is to use a comparator. There is a similar question and answer here... Best way to list files in Java, sorted by Date Modified?
您最好的選擇是使用比較器。這里有一個類似的問題和答案...在Java中列出文件的最佳方法,按修改日期排序?
#3
0
I would use FileUtils in commons-io to get back the Collection of Files. I would then apply a custom comparator. It should be pretty easy.
我會在commons-io中使用FileUtils來獲取文件集合。然后我會應用自定義比較器。應該很容易。