Languages
[Edit]
EN

Java - list all directories from directory

0 points
Created by:
Emerson-V
303

In this article, we would like to show you how to list all directory names from the directory in Java.

Quick solution:

File[] directories = new File(path).listFiles(File::isDirectory); // get array of directories

 

Practical example

In this example, we use listFiles() method and check if the file is a directory to list all directories from the directory specified by path.

Java - list all directories (example data)
Java - list all directories (example data)

Example.java: 

import java.io.File;
import java.util.Objects;

public class Example {

    public static void main(String[] args) {
        String path = "C:\\projects\\example";
        File[] directories = new File(path).listFiles(File::isDirectory); // array of directories

        File[] list = Objects.requireNonNull(directories); // creates list if directories != null

        for (File item : list) {
            System.out.println(item.getName());
        }
    }
}

Result:

Folder1
Folder2

Note:

To get full directory paths instead of firectory names remove getName() from item.getName() inside for loop.

Result:

C:\projects\example\Folder1
C:\projects\example\Folder2

References

Alternative titles

  1. Java - get all directory names from directory
  2. Java - list only directories from directory
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join