Reputation: 5367
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?
Upvotes: 0
Views: 509
Reputation: 659
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() );
}
Upvotes: 1
Reputation: 6637
Have a look at the docs of Files#find
: the third param is a function used to decide whether a file should be included in the returned stream. You're not adding anything to the dirs
list.
Try this where the matcher function filters for directories:
List<Path> found = Files.find(start,
Integer.MAX_VALUE,
(path, basicFileAttributes) -> path.toFile().isDirectory()).collect(Collectors.toList());
java.lang.System.out.println(found.size());
Upvotes: 1
Reputation: 4266
You could use File.isDirectory()
to count them:
static int countSub(File[] directory) {
int total = 0;
for (File files : directory) {
if (files.isDirectory()) {
total++;
}
}
return total;
}
Upvotes: -1