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_
2008-11-13 00:58:40
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
2008-11-13 01:05:20
It's kind of wonky to force a ClassCastException in the non-File case, instead of, say, asserting instanceof.
Chris Conway
2008-11-13 01:10:16
You won't get a non-File from the array returned by File.listFiles();
OscarRyz
2008-11-13 01:17:25
Right. So assert that.
Chris Conway
2008-11-13 19:07:49
+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
2008-11-13 01:13:52
+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
2008-11-13 14:21:57