简体   繁体   中英

How to get the most recent file of a directory in Java

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM