Java 8:从文件夹/子文件夹中获取文件[重复]

问题描述 投票:7回答:2

我在Spring Boot应用程序的resources文件夹中有这个文件夹。

resources/files/a.txt
resources/files/b/b1.txt
resources/files/b/b2.txt
resources/files/c/c1.txt
resources/files/c/c2.txt

我想得到所有的txt文件,所以这是我的代码:

   ClassLoader classLoader = this.getClass().getClassLoader();
   Path configFilePath = Paths.get(classLoader.getResource("files").toURI());   

   List<Path> atrackFileNames = Files.list(configFilePath)
                .filter(s -> s.toString().endsWith(".txt"))
                .map(Path::getFileName)
                .sorted()
                .collect(toList());

但我只得到文件a.txt

java collections java-8 functional-programming stream
2个回答
21
投票
Files.walk(configFilePath)
     .filter(s -> s.toString().endsWith(".txt"))
     .map(Path::getFileName)
     .sorted()
     .collect(Collectors.toList());

5
投票

Files.list(path)方法仅返回目录中的文件流。并且方法列表不是递归的。 而不是你应该使用Files.walk(path)。此方法遍历以给定起始目录为根的所有文件树。 更多关于它: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-

© www.soinside.com 2019 - 2024. All rights reserved.