Files class Find method

1. Overview

In this article we will look at Files class’s find method. find() method returns the content of directory passed in parameter based on condition(BiPredicate). The contents are returned lazily in Stream object that contains Path to all the contents in directory. find() is like enhanced version of walk() method as you can traverse the directory structure based on some condition.

The listing returned in Stream is recursive and traversed in depth first search traversal manner. Which means that the listing provided will navigate directory/directories.

2. find(..) method

Find method parameters :

  1. Path : Path from which our search will begin.
  2. int maxDepth : maxdepth of the directories to search
  3. BiPredicate<Path, BasicFileAttributes> matcher : criteria to search
  4. FileVisitOption… options : FileVisitOptions

Below is the code for printing paths of files.

String resourcesPath = getClass().getResource("/Text-Files")
                                 .toURI().getPath();
 
BiPredicate<Path, BasicFileAttributes> matcher = 
      (path, fileAtt) -> (fileAtt.isRegularFile());
 
Files.find(Paths.get(resourcesPath), 10, matcher)
     .forEach(System.out::println);

This is a very simple example but we can do a lot using BasicFileAttributes. Check out the documentation of BasicFileAttributes and play around with different methods.

3. Conclusion

In this article, we saw how to use the find() method to traverse a directory several levels and returns files based on condition. Feel free to play around using different examples. find() is a powerful method as it allows us to use all the methods of Stream interface.

Leave a Reply

Your email address will not be published. Required fields are marked *