iaacp iaacp - 16 days ago 7
Java Question

How to find sub-directories in a directory/folder?

I'm looking for a way to get all the names of directories in a given directory, but not files.

For example, let's say I have a folder called

Parent
, and inside that I have 3 folders:
Child1
Child2
and
Child3
.

I want to get the names of the folders, but don't care about the contents, or the names of subfolders inside Child1, Child2, etc.

Is there a simple way to do this?

Answer

You can use String[] directories = file.list() to list all file names, then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.

For example:

File file = new File("C:\\Windows");
String[] names = file.list();

for(String name : names)
{
    if (new File("C:\\Windows\\" + name).isDirectory())
    {
        System.out.println(name);
    }
}