EN
Java - get directories from a specific directory (recursive)
0
points
In this article, we would like to show you how to get all directories from a specific directory (including subdirectories) in Java.
Practical example
Project structure:
project/
βββ one.txt
βββ directory1/
βββ directory3/
βββ two.json
βββ directory2/
βββ three.html
1. Using File.listFiles
method.
import java.io.File;
public class Example {
public static void listDirectoriesInDirectory(File directoryPath) {
File[] filesList = directoryPath.listFiles();
for (File file : filesList) {
if (file.isDirectory()) {
System.out.println(file);
listDirectoriesInDirectory(file);
}
}
}
public static void main(String[] args) {
File directoryPath = new File("C:\\project");
listDirectoriesInDirectory(directoryPath);
}
}
Output:Β
C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2
2. Using Files.find
method.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Files.find(Paths.get("C:\\project"),
Integer.MAX_VALUE, // the maximum number of directory levels to search
(filePath, FileAttributes) -> FileAttributes.isDirectory())
.forEach(System.out::println);
}
}
Output:
C:\project
C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2
3. Using Files.walk
Β method.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:\\project"))
.filter(Files::isDirectory)
.forEach(System.out::println);
}
}
Output:Β
C:\project
C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2