【问题标题】:Java recursively list the files from directory of specific patternJava递归列出特定模式目录中的文件
【发布时间】:2020-06-03 07:23:52
【问题描述】:

我有下面的目录/文件结构

ABC
  -- Apps
  -- Tests
     -- file1.xml
     -- file2.xml
  -- AggTests
  -- UnitTests
PQR
  -- Apps
  -- Tests
     -- file3.xml
     -- file4.xml
  -- AggTests
  -- UnitTests

在这里,我只想获取Tests 目录中的文件列表。我如何在java中实现它,我发现这很有帮助https://stackoverflow.com/a/24006711/1665592

下面列出了所有 XML 文件,但我需要它来自名为 Tests 的特定目录?

try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {

    List<String> fileList = walk.map(x -> x.toString())
            .filter(f -> f.endsWith(".xml")).collect(Collectors.toList());

    fileList.forEach(System.out::println);

} catch (IOException e) {
    e.printStackTrace();
}

最终,我需要fileList = [file1.xml, file2.xml, file3.xml, file4.xml]

【问题讨论】:

    标签: java file recursion filepath filepattern


    【解决方案1】:
    List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.toString())
                        .filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
    

    如果您只需要文件名,而不需要整个路径,您可以这样做:

    List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.getFileName().toString())
                        .filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
    

    【讨论】:

    • 谢谢@viral-verma,我正在寻找完整的文件路径。但是,是的,这两个例子都可以通过这个社区帮助某人
    【解决方案2】:
    public List<String> getAllFiles(String baseDirectory,String filesParentDirectory) throws IOException{
           return Files.walk(Paths.get(baseDirectory))
                   .filter(Files::isRegularFile)
                   .filter(x->(x.getParent().getFileName().toString().equals(filesParentDirectory)))
                   .map(x->x.getFileName().toString()).collect(Collectors.toList());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2017-12-19
      相关资源
      最近更新 更多