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:
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
.
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()
fromitem.getName()
inside for loop.Result:
C:\projects\example\Folder1 C:\projects\example\Folder2