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

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

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

9条回答
  •  春和景丽
    2020-11-28 10:22

    Java 8

    Optional findLastModifiedFile(Path directory) throws IOException {
        return Files.list(directory)
                .max(this::compareLastModified);
    }
    
    int compareLastModified(Path p1, Path p2) {
        try {
            return Files.getLastModifiedTime(p1).compareTo(Files.getLastModifiedTime(p2));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    

提交回复
热议问题