Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - get the newest file in a directory?

People also ask

How to get latest file name from directory in Java?

The legacy java.io package provides the File class to encapsulate an abstract representation of file and directory pathnames. Thankfully, the File class comes with a handy method called lastModified(). This method returns the last modified time of the file denoted by an abstract pathname.

How to get last folder name from path in Java?

getName() documentation: Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.


The following code returns the last modified file or folder:

public static File getLastModified(String directoryFilePath)
{
    File directory = new File(directoryFilePath);
    File[] files = directory.listFiles(File::isFile);
    long lastModifiedTime = Long.MIN_VALUE;
    File chosenFile = null;

    if (files != null)
    {
        for (File file : files)
        {
            if (file.lastModified() > lastModifiedTime)
            {
                chosenFile = file;
                lastModifiedTime = file.lastModified();
            }
        }
    }

    return chosenFile;
}

Note that it required Java 8 or newer due to the lambda expression.


In Java 8:

Path dir = Paths.get("./path/somewhere");  // specify your directory

Optional<Path> lastFilePath = Files.list(dir)    // here we get the stream with full directory listing
    .filter(f -> !Files.isDirectory(f))  // exclude subdirectories from listing
    .max(Comparator.comparingLong(f -> f.toFile().lastModified()));  // finally get the last file using simple comparator by lastModified field

if ( lastFilePath.isPresent() ) // your folder may be empty
{
    // do your code here, lastFilePath contains all you need
}     

This works perfectly fine for me:

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;

...

/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
    File theNewestFile = null;
    File dir = new File(filePath);
    FileFilter fileFilter = new WildcardFileFilter("*." + ext);
    File[] files = dir.listFiles(fileFilter);

    if (files.length > 0) {
        /** The newest file comes first **/
        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        theNewestFile = files[0];
    }

    return theNewestFile;
}

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;
}