java 按日期排列文件_如何在java中按日期對目錄中的文件進行排序? [重復]

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來獲取文件集合。然后我會應用自定義比較器。應該很容易。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值