EN
Java - list all directories from directory
0 points
In this article, we would like to show you how to list all directory names from the directory in Java.
Quick solution:
xxxxxxxxxx
1
File[] directories = new File(path).listFiles(File::isDirectory); // get array of directories
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
.

Example.java:
xxxxxxxxxx
1
import java.io.File;
2
import java.util.Objects;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String path = "C:\\projects\\example";
8
File[] directories = new File(path).listFiles(File::isDirectory); // array of directories
9
10
File[] list = Objects.requireNonNull(directories); // creates list if directories != null
11
12
for (File item : list) {
13
System.out.println(item.getName());
14
}
15
}
16
}
Result:
xxxxxxxxxx
1
Folder1
2
Folder2
Note:
To get full directory paths instead of firectory names remove
getName()
fromitem.getName()
inside for loop.Result:
xxxxxxxxxx
1C:\projects\example\Folder1
2C:\projects\example\Folder2