Java recursively list the files from directory of specific pattern

283 Views Asked by At

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]

2

There are 2 best solutions below

1
On BEST ANSWER
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());
0
On
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());
    }