The Files.walk API is available in Java 8, it is recommended to use try-with-resources to close the Files.walk stream.
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) {
//...
1. List all files.
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) {
List result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
2. List all folders.
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) {
List result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
3. List all files end with .txt
try (Stream walk = Files.walk(Paths.get("C:\\projects"))) {
List result = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".txt")).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
References