Search code examples
javafilerecursionfilepathfilepattern

Java recursively list the files from directory of specific pattern


I've below directory/file structure

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

Here I just want to a List of Files from Tests directory. How can I achieve it in java, I found this is something helpful https://stackoverflow.com/a/24006711/1665592

Something below is listing down all XML files but I need it from specific directory called 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();
}

Ultimately, I need fileList = [file1.xml, file2.xml, file3.xml, file4.xml]


Solution

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

    if you just need the filenames, without the whole path, you could do:

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