Files.newDirectoryStream with filter recursive

868 Views Asked by At

I had the following code:

Path dir = Paths.get("My root dir/Folder1");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.xml")) {
        for (Path entry : stream) {
            // Do something
        }
} catch (IOException e) {
        //
}

Now the folder structure changed and I can have both:

My root dir
-- Folder1
---- MyFile.xml

or

My root dir
-- Folder1_MyFile.xml

So I would like to be able to use the following code:

Path dir = Paths.get("My root dir/Folder1");
String pattern = "Folder1/*.xml"; // or "Folder1_*.xml"
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, pattern)) {
        for (Path entry : stream) {
            // Do something
        }
}

In this case, I would only have to change the pattern variable, with a value of "Folder1/*.xml" or "Folder1_*.xml". The first one ("Folder1/*.xml") doesn't work because Files.newDirectoryStream is not recursive and only try to match the files/folders at the first level in the dir folder.

Is there any way to use the Files.newDirectoryStream(Path dir, String glob) method this way (filtering files recursively) or do I have to make myself a recursive method that retrieves ALL the files/folders and manually filter them ? (I would rather not use external libraries)

Thanks.

0

There are 0 best solutions below