Java - get the newest file in a directory?

后端 未结 9 1397
难免孤独
难免孤独 2020-12-01 02:13

Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

9条回答
  •  醉话见心
    2020-12-01 02:29

    In Java 8:

    Path dir = Paths.get("./path/somewhere");  // specify your directory
    
    Optional 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
    }     
    

提交回复
热议问题