Files.find
The signature of find looks as follows :
Stream find (Path start, int maxDepth, BiPredicate matcher, FileVisitOption… options) throws IOException
The find method enables us to find a file, starting from a path, going x-levels deep. A BiPredicate interface will determine which files are returned and which not. The BiPredicate’s abstract method has the following signature :
boolean test(T t, U u)
If the file complies with the test, it will be returned, otherwise not. So let’s look at an example:
1
2
3
4
Path start = new File("/u02").toPath();
BiPredicate topicDirectoriesMatcher = (path, basicFileAttributes) -> basicFileAttributes.isRegularFile() && path.toString().contains("1");
Stream pathStream = Files.find(start, 2, topicDirectoriesMatcher);
pathStream.sorted().forEach(System.out::println);
results in :
>/u02/dir1/file1.txt
>/u02/dir1/file2.txt
>/u02/dir1/file3.txt
The key here is the BiPredicate object ‘topicDirectoriesMatcher’. Path and basicFileAttributes are the parameters of the Test method, and the implementation is :
basicFileAttributes.isRegularFile() && path.toString().contains(“1”);
Meaning : only return me the regular files, not the directories, and the path should contain the character ‘1’. If we would replace .isRegularFile() by isDirectory() we would only get the result :
>/u02/dir1