views:

3527

answers:

4

Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

+3  A: 

Take a look at this question:

Best way to list files in Java, sorted by Date Modified?

Also listed in there is the Apache Commons IO package. That has LastModifiedFileComparator.

Hates_
A: 

Something like:

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;


public class Newest {
    public static void main(String[] args) {
        File dir = new File("C:\\your\\dir");
        File [] files  = dir.listFiles();
        Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}
OscarRyz
It's kind of wonky to force a ClassCastException in the non-File case, instead of, say, asserting instanceof.
Chris Conway
You won't get a non-File from the array returned by File.listFiles();
OscarRyz
Right. So assert that.
Chris Conway
+3  A: 

This returns the last modified:

public static File lastFileModified(String dir) {
 File fl = new File(dir);
 File[] files = fl.listFiles(new FileFilter() {   
  public boolean accept(File file) {
   return file.isFile();
  }
 });
 long lastMod = Long.MIN_VALUE;
 File choise = null;
 for (File file : files) {
  if (file.lastModified() > lastMod) {
   choise = file;
   lastMod = file.lastModified();
  }
 }
 return choise;
}
José Leal
Remember to check that listFiles() doesn't return null.
Zach Scrivena
+1  A: 

@Oscar's example can be simplified for Java 5:

public class Newest {
    public static void main(String[] args) {
        File dir = new File("foo/bar/baz");
        File[] files = dir.listFiles();
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f2.lastModified()).compareTo(
                        f1.lastModified());
            }
        });
        System.out.println(Arrays.asList(files));
    }
}
toolkit