Java 8 List all Files in Directory and Subdirectories

List All Files in Directory and Subdirectories

Files.walk Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

Files.list Method Return a lazily populated Stream for the current directory only,Files.walk can be used to get list of files from Directory & Subdirectories .

Example 1: List All Files in Directory and Subdirectories
List All Files in Directory and Subdirectories
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

public static void main(String[] args) throws IOException {

Path start = Paths.get("C:\\data\\");
try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
List<String> collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());

collect.forEach(System.out::println);
}


}

Note

Files.walk method takes int maxDepth as parameter. The maxDepth parameter is the maximum number of levels of directories to visit.
MAX_VALUE may be used to indicate that all levels should be visited. Value 1 can be used to list files in current Directory.

Example 2: List All Files in Current Directory only
List All Files in Current Directory only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public static void main(String[] args) throws IOException {

Path start = Paths.get("C:\\data\\");
try (Stream<Path> stream = Files.walk(start, 1)) {
List<String> collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());

collect.forEach(System.out::println);
}


}

Share Comments