Search code examples
javanio

java nio Files.find to count subdirectories


I was expecting this code using Java 8's Files#find method from a java.nio.File to return a count of all the sub directories of the current directory:

public static void main(String[] args) throws IOException {
    List<File> dirs = new LinkedList<File>();
    Files.find(Paths.get("."),
               Integer.MAX_VALUE,
               (path, basicFileAttributes) -> dirs.add(path.toFile()));
    System.out.println(dirs.size());
}

however, it always outputs 0. Where is my misunderstanding?


Solution

  • Files.find returns stream, which you haven't consumed hence the lambda you passed to add files to dirs not executed. stream should be consumed, try the following

    `

    public static void main(String[] args) throws IOException {
    
          List<File> dirs = new LinkedList<File>();
          Files.find(Paths.get("."),
                 Integer.MAX_VALUE,
                (path, basicFileAttributes) -> 
          dirs.add(path.toFile())).forEach((ignore)->{});
    
         java.lang.System.out.println( dirs.size() );
    }