How to list files in a directory in Java
[CG]BOUGA
5,691 views
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// {
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
// }
Path directory = Paths.get("/");
// Method 1: get the files in the given directory
Files.list(directory)
.filter(Files::isDirectory)
.forEach(System.out::println);
// Method 2: recursively run through the tree (at a maximum depth of 2)
Files.walk(directory, 2)
.filter(Files::isRegularFile)
.forEach(System.out::println);
//{
}
}
//}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.