Number of subfolders in a folder directory

directory, java, subdirectory

Solution

You can use `FileFilter` to list only directories:

File file = new File("/tmp");
File[] files = file.listFiles(new FileFilter() {
    @Override
    public boolean accept(File f) {
        return f.isDirectory();
    }
});
System.out.println("Folders count: " + files.length);

Java `File` class is an example of the Composite Design Pattern, so you have to actually ask the instance if it's a file: `isFile()` or if it's a directory `isDirectory()`.

If you want to count directories, and you're using Java 8. `Files.find` function, can do the same thing in a more concise manner (practically one-liner):

long count = Files.find(
    Paths.get("/tmp"), 
    1,  // how deep do we want to descend
    (path, attributes) -> attributes.isDirectory()
).count() - 1; // '-1' because '/tmp' is also counted in

Problem

I have a folder which consists of both datafiles (`.txt` etc) and subfolders. In Java, how would I accomplish getting the number of subfolders in any specified directory path? (so excluding the datafiles; only counting the subfolders) I have read about counting the number of `.txt` files but can't seem to find anything about counting subfolders only. I have no idea where to start but to give you an idea: ``` String directory = "C:\Users\ . \Desktop\ . \workspace\src\testfolder"; int numberOfSubfolders; //what is numberOfSubfolders in testfolder? ``` All help appreciated.

Original source