Reputation: 324
Let's say that I have a specific directory on a system (specifically Ubuntu) with say backups or logs generated by other programs. How would I locate and open the most recently created (or modified) file as a File
in Java?
I will need a solution that does not rely on a scenario where filenames are named after a timestamp or sequential names like log1,log2, etc...
. Subdirectories will be ignored.
Upvotes: 3
Views: 7815
Reputation: 129
Second answer to this question should do what you want:
stackoverflow.com/questions/2064694/how-do-i-find-the-last-modified-file-in-a-directory-in-java
file.lastModified()
gives you the time a specific file was last modified, you can simply get that time for every file and then loop over the times to find the "newest" time.
Question seems to be a duplicate of the one asked in the link.
Upvotes: 0
Reputation: 5072
You can loop through files for directory and compare them and find the last modified one.
public File getLastModifiedFile(File directory) {
File[] files = directory.listFiles();
if (files.length == 0) return null;
Arrays.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
return new Long(o2.lastModified()).compareTo(o1.lastModified());
}});
return files[0];
}
To get last modified time:
File file = getLastModifiedTime("C:\abcd");
long lastModified = file != null ? file.lastModified() : -1 // -1 or whatever convention you want to infer no file exists
Upvotes: 1