簡體   English   中英

Java 遞歸列出特定模式目錄中的文件

[英]Java recursively list the files from directory of specific pattern

我有以下目錄/文件結構

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]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM