用Java取文件夹下最新文件

我想从一个文件夹下取出最新的一个文件,然后把它的文件名显示出来.想了一个办法,可能是比较笨的方法,希望能抛砖引玉.

解决方案是:

1, 遍历文件夹下的所有文件,将文件名和文件的最后修改时间push到一个Map中,用Last Modified time作为key,file name作为value.
<code>

List dateList = new ArrayList();

public Map readfile(String filepath){
Map map = null;
try {
map = new TreeMap();
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println(filepath+" is not a folder!");
}else if (file.isDirectory()) {

String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "/" + filelist[i]);
if (!readfile.isDirectory()) {
String fileName = readfile.getName();
long time = readfile.lastModified();
dateList.add(new Long(time));
map.put(String.valueOf(time), fileName);
}
}
}

}catch (Exception e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return map;
}

</code>

2. 将这个Map的Key按时间排序.


<code>
Collections.sort(dateList,new Comparator(){
public int compare(Object o1,Object o2) {
Long p1 = (Long)o1;
Long p2 = (Long)o2;
if(p1.longValue()<p2.longValue())
return 1;
else
return 0;
}});
</code>

3.根据排好序的key取出文件名,那么第一个就是我们所要的最新的文件了.

<code>
String date = null;
String fileName = null;

if(map!=null && map.size()!=0){
for(int i=0; i<dateList.size(); i++){
date = String.valueOf(dateList.get(i));
fileName = (String)map.get(date);
break;
}
}
System.out.println("The newest file is: " + fileName);
</code>

Refer to www.jssay.com
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值