javajava-8directoryfilesystemsnio

Find a file in a directory and sub directories using Java 8


How to implement an algorithm in Java 8, given a start directory and a filename, that searches for the file in the given directory or any subdirectories, which are nested not deeper than five levels?

For example, consider the following directory structure:

Folder 1
   Folder 2
      Folder 3
        Folder 4
            Folder 5
                Folder 6
                    nfiles.txt…
                MyFile.txt
                xfile.txt
            filesInFolder4…
        filesInFolder3…
   …

The algorithm should search for the file up to files Folder 5 and report, if a file with the given filename exists.

How to do that using Java 8?


Solution

  • Please have a look at Files.find method.

    try (Stream<Path> stream = Files.find(Paths.get("Folder 1"), 5,
                (path, attr) -> path.getFileName().toString().equals("Myfile.txt") )) {
            System.out.println(stream.findAny().isPresent());
    } catch (IOException e) {
            e.printStackTrace();
    }