Java 8:从文件夹/子文件夹获取文件

9

我有一个SpringBoot应用程序的资源文件夹中有这些文件夹。

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

2个回答

26
    Path configFilePath = FileSystems.getDefault()
            .getPath("C:\\Users\\sharmaat\\Desktop\\issue\\stores");

    List<Path> fileWithName = Files.walk(configFilePath)
            .filter(s -> s.toString().endsWith(".java"))
            .map(Path::getFileName).sorted().collect(Collectors.toList());

    for (Path name : fileWithName) {
        // printing the name of file in every sub folder
        System.out.println(name);
    }

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接