Java 8中提供了Files.walk
API,建议使用try-with-resources
关闭Files.walk
流。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
//...
}
1.列出所有文件。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
2.列出所有文件夹。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
3.列出所有以.txt
结尾的文件
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".txt")).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}