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

3

23

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?

Assail answered 23/11, 2012 at 17:24 Comment(3)
Do you know how many levels it could have? Or could it be any number?Virile
@Quoi no, this is not for homework.Assail
@Aaron It shouldn't be more than 2 levels deep. Meaning A parent folder, a child subfolder, and then there should be no more deeper than that.Assail
C
23

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);
    }
}
Cotemporary answered 23/11, 2012 at 17:30 Comment(4)
What's "C\\Windows\\" , list() returns the absolutePathZitazitah
That sounds great! If I don't know exactly what the path will be up until a certain point, say "..\\Projects\\Tests\\Test1" being the only known part of the directory, will I still be able to do it this way?Assail
You mean the input will be a relative path? Because if we don't provide an absolute path, the program will treat it as a relative path to running program's current path. For example, if program's path is C:\\Project\\Test, and we input a pathname abc, then the program will treat it as C:\\Project\\Test\\abcCotemporary
@Cotemporary sorry but I'm not clear. What if I don't know the path before the Project directory? I'd like to run this on multiple computers, but each time from my Eclipse project. What would my File object look like when initialized?Assail
K
24

If you are on java 7, you might wanna try using the support provided in

package java.nio.file 

If your directory has many entries, it will be able to start listing them without reading them all into memory first. read more in the javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)

Here is also that example adapted to your needs:

public static void main(String[] args) {
    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path file) throws IOException {
            return (Files.isDirectory(file));
        }
    };

    Path dir = FileSystems.getDefault().getPath("c:/");
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
        for (Path path : stream) {
            // Iterate over the paths in the directory and print filenames
            System.out.println(path.getFileName());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Kalasky answered 24/11, 2012 at 8:28 Comment(1)
And on Java 8, you could simplify to: Files.newDirectoryStream(dir, p -> Files.isDirectory(p))Artemisia
C
23

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);
    }
}
Cotemporary answered 23/11, 2012 at 17:30 Comment(4)
What's "C\\Windows\\" , list() returns the absolutePathZitazitah
That sounds great! If I don't know exactly what the path will be up until a certain point, say "..\\Projects\\Tests\\Test1" being the only known part of the directory, will I still be able to do it this way?Assail
You mean the input will be a relative path? Because if we don't provide an absolute path, the program will treat it as a relative path to running program's current path. For example, if program's path is C:\\Project\\Test, and we input a pathname abc, then the program will treat it as C:\\Project\\Test\\abcCotemporary
@Cotemporary sorry but I'm not clear. What if I don't know the path before the Project directory? I'd like to run this on multiple computers, but each time from my Eclipse project. What would my File object look like when initialized?Assail
T
1
public static void displayDirectoryContents(File dir) {
    try {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory Name==>:" + file.getCanonicalPath());
                displayDirectoryContents(file);
            } else {
                System.out.println("file Not Acess===>" + file.getCanonicalPath());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

====inside class/Method provide File=URL ======

    File currentDir = new File("/home/akshya/NetBeansProjects/");
    displayDirectoryContents(currentDir);
}
Tolkan answered 14/5, 2015 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.