【问题标题】:Java 8 : Get files from folder / subfolder [duplicate]Java 8:从文件夹/子文件夹中获取文件[重复]
【发布时间】:2018-07-11 20:02:04
【问题描述】:

我在 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

【问题讨论】:

    标签: java collections java-8 functional-programming stream


    【解决方案1】:
        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);
        }
    

    【讨论】:

      【解决方案2】:

      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...-

      【讨论】:

        猜你喜欢
        • 2016-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-07
        • 1970-01-01
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多