---
title: "用Java取文件夹下最新文件"
author: "jssay"
date: "2009-10-21T12:41:49Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2009-10-21T12:41:49Z"
id: 498081
url: "https://jssay.iteye.com/blog/498081"
---

我想从一个文件夹下取出最新的一个文件,然后把它的文件名显示出来.想了一个办法,可能是比较笨的方法,希望能抛砖引玉.

解决方案是:

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*);
                  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