Java, List only subdirectories from a directory, not files

file, java

Solution

You can use the File class to list the directories.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

Update

Comment from the author on this post wanted a faster way, great discussion here: How to retrieve a list of directories QUICKLY in Java?

Basically:

- If you control the file structure, I would try to avoid getting into that situation.

- In Java NIO.2, you can use the directories function to return an iterator to allow for greater scaling. The directory stream class is an object that you can use to iterate over the entries in a directory.

Problem

In Java, How do I list only subdirectories from a directory? I'd like to use the java.io.File functionality, what is the best method in Java for doing this?

Original source

Related problems