How do I find the last modified file in a directory in java?
How do I find the last modified file in a directory in java?
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;
}
Combine these two:
File.lastModified().File.listFiles().Note that in Java the java.io.File object is used for both directories and files.
You can retrieve the time of the last modification using the File.lastModified() method. My suggested solution would be to implement a custom Comparator that sorts in lastModified()-order and insert all the Files in the directory in a TreeSet that sorts using this comparator.
Untested example:
SortedSet<File> modificationOrder = new TreeSet<File>(new Comparator<File>() {
public int compare(File a, File b) {
return (int) (a.lastModified() - b.lastModified());
}
});
for (File file : myDir.listFiles()) {
modificationOrder.add(file);
}
File last = modificationOrder.last();
The solution suggested by Bozho is probably faster if you only need the last file. On the other hand, this might be useful if you need to do something more complicated.
Your problem is similar to: How to get only 10 last modified files from directory using Java?
Just change the filter code to have only one File and the accept method should simply compare the two time stamps.
Untested code:
class TopFileFilter implements FileFilter {
File topFile;
public boolean accept(File newF) {
if(topFile == null)
topFile = newF;
else if(newF.lastModified()>topFile.lastModified())
topFile = newF;
return false;
}
}
Now, call dir.listFiles with an instance of this filter as argument. At the end, the filter.topFile is the last modified file.
The comparator in Emil's solution would be cleaner this way
public int compare(File a, File b) {
if ((a.lastModified() < b.lastModified())) {
return 1;
} else if ((a.lastModified() > b.lastModified())) {
return -1;
}
return 0;
}
Casting (a.lastModified() - b.lastModified()) to int can produce unexpected results.