[java] Java, List only subdirectories from a directory, not files

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?

This question is related to java file

The answer is


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:

  1. If you control the file structure, I would try to avoid getting into that situation.
  2. 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.

Similar questions with java tag:

Similar questions with file tag: