Java Files.walk示例

转自:https://blog.csdn.net/cyan20115/article/details/106548324

Java 8中提供了Files.walk API

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();
}

4.获得所有文件

List<File> filesInFolder= new ArrayList<>();
try (Stream<Path> walk = Files.walk(Paths.get(fileCatalogue))){
       filesInFolder= walk.filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toList());
}catch (IOException e){
      e.printStackTrace();
}

 

posted on 2022-09-29 17:54  大山008  阅读(1132)  评论(0)    收藏  举报