-4

How do I find the last modified file in a directory with java? get file name of last file modified java EXP: i have: test_4755_err.log. test_4588_err.log. test_14587_err.log.` i wanna get thé last file between this files

1 Answers1

0

Are you just looking for the file that was last modified? You could do:

File lastModified = null;
String directory = "."; // replace with your directory
File[] files = new File(directory).listFiles();
if(files != null){
    Arrays.sort(files, new Comparator<File>(){
        @Override
        public int compare(File o, File t){
            // reverse the ordering so the newest file is first in the array
            return -1 * Long.compare(o.lastModified(), t.lastModified());
        }
    });
    lastModified = files[0];
}

As pointed out, this would be more efficient:

File newest = null
for(File f : new File(dir).listFiles()){
    if(newest == null || f.lastModified() > newest.lastModified()){
        newest = f;
    }
}
Ryan S
  • 370
  • 2
  • 12
  • 1
    If you're just looking for the newest file or the oldest file, it's wasteful to bring all of them into an array and sort them. You could just iterate over the files and keep the newest-so-far. Iterating over the files is O(n), while sorting them is O(nlogn). – Kenster May 16 '14 at 16:23