In this topic, I am sharing very interesting and useful code for Many developers.
Requires:
Environment: Java 8
Package: java.nio.*
public static Optional<Path> getLatestFile ( String directory ) throws IOException Path dir = Paths.get(directory); // specify your directory Optional<Path> lastFilePath = Files.list(dir) .filter(f -> Files.isDirectory(f) == false) .max((f1, f2) -> (int)(f1.toFile().lastModified() - f2.toFile().lastModified())); return lastFilePath; // here we get the stream with full directory listing // exclude subdirectories from listing // finally get the last file using simple comparator by lastModified field
Call the method like this:
Optional<Path> optional = getLatestFile("C:/");
System.out.println( optional.get().toString() );


Leave a comment