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)?
private File getLatestFilefromDir(String dirPath){
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
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 ));
}
}
This will return the most recent created file, I made this because when you create a file in some situations, it may not always have the correct modified date.
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
private File lastFileCreated(String dir) {
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return true;
}
});
FileTime lastCreated = null;
File choice = null;
for (File file : files) {
BasicFileAttributes attr=null;
try {
attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}catch (Exception e){
System.out.println(e);
}
if(lastCreated ==null)
lastCreated = attr.creationTime();
if (attr!=null&&attr.creationTime().compareTo(lastCreated)==0) {
choice = file;
}
}
return choice;
}