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.
Project structure:
xxxxxxxxxx
1
project/
2
├── one.txt
3
└── directory1/
4
├── directory3/
5
└── two.json
6
└── directory2/
7
└── three.html
xxxxxxxxxx
1
import java.io.File;
2
3
public class Example {
4
5
public static void listDirectoriesInDirectory(File directoryPath) {
6
File[] filesList = directoryPath.listFiles();
7
for (File file : filesList) {
8
if (file.isDirectory()) {
9
System.out.println(file);
10
listDirectoriesInDirectory(file);
11
}
12
}
13
}
14
15
public static void main(String[] args) {
16
File directoryPath = new File("C:\\project");
17
listDirectoriesInDirectory(directoryPath);
18
}
19
}
Output:
xxxxxxxxxx
1
C:\project\directory1
2
C:\project\directory1\directory3
3
C:\project\directory2
xxxxxxxxxx
1
import java.nio.file.Files;
2
import java.nio.file.Paths;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
Files.find(Paths.get("C:\\project"),
9
Integer.MAX_VALUE, // the maximum number of directory levels to search
10
(filePath, FileAttributes) -> FileAttributes.isDirectory())
11
.forEach(System.out::println);
12
}
13
}
Output:
xxxxxxxxxx
1
C:\project
2
C:\project\directory1
3
C:\project\directory1\directory3
4
C:\project\directory2
xxxxxxxxxx
1
import java.nio.file.Files;
2
import java.nio.file.Paths;
3
import java.io.IOException;
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
Files.walk(Paths.get("C:\\project"))
9
.filter(Files::isDirectory)
10
.forEach(System.out::println);
11
}
12
}
Output:
xxxxxxxxxx
1
C:\project
2
C:\project\directory1
3
C:\project\directory1\directory3
4
C:\project\directory2