iaacp iaacp - 1 year ago 73
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

, and inside that I have 3 folders:

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 Source

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download