2

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]

Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92

2 Answers2

2
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());
Aviral Verma
  • 488
  • 4
  • 11
1
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());
    }
rohit prakash
  • 565
  • 6
  • 12