How do I find the last modified file in a directory in Java?

后端 未结 9 929
半阙折子戏
半阙折子戏 2020-11-28 09:51

How do I find the last modified file in a directory in java?

9条回答
  •  甜味超标
    2020-11-28 10:27

    Let's assume that the variable thePath contains the directory we want to search, the following snippet returns the last modified file inside it:

    Files.walk(thePath)
    .sorted((f1, f2) -> -(int)(f1.toFile().lastModified() - f2.toFile().lastModified()))
    .skip(1)
    .findFirst()
    

    What it does is:

    • first sort the files by their last modification time in reverse,
    • then skip the directory itself,
    • and finally take the first element in the stream (which is the last modified one).

提交回复
热议问题