Find files in a folder using Java

前端 未结 12 1924
日久生厌
日久生厌 2020-11-28 08:15

What I need to do if Search a folder say C:\\example

I then need to go through each file and check to see if it matches a few start characters so if fil

12条回答
  •  独厮守ぢ
    2020-11-28 08:41

    As of Java 1.8, you can use Files.list to get a stream:

    Path findFile(Path targetDir, String fileName) throws IOException {
        return Files.list(targetDir).filter( (p) -> {
            if (Files.isRegularFile(p)) {
                return p.getFileName().toString().equals(fileName);
            } else {
                return false;
            }
        }).findFirst().orElse(null);
    }
    

提交回复
热议问题