11

Is there a way using ResourceLoader to get a list of "sub resources" in a directory in the jar?

For example, given sources

src/main/resources/mydir/myfile1.txt
src/main/resources/mydir/myfile2.txt

and using

@Autowired
private ResourceLoader resourceLoader;

I can get to the directory

Resource dir = resourceLoader.getResource("classpath:mydir")
dir.exists() // true

but not the files within the dir. If I could get the file, I could call dir.getFile().listFiles(), but

dir.getFile() // explodes with FileNotFoundException

But I can't find a way to get the "child" resources.

Bohemian
  • 412,405
  • 93
  • 575
  • 722

2 Answers2

19

You can use a ResourcePatternResolver to get all the resources that match a particular pattern. For example:

Resource[] resources = resourcePatternResolver.getResources("/mydir/*.txt")

You can have a ResourcePatternResolver injected in the same way as ResourceLoader.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
3

Based on Bohemian's comment and another answer, I used the following to get an input streams of all YAMLs under a directory and sub-directories in resources (Note that the path passed doesn't begin with /):

private static Stream<InputStream> getInputStreamsFromClasspath(
        String path,
        PathMatchingResourcePatternResolver resolver
) {
    try {
        return Arrays.stream(resolver.getResources("/" + path + "/**/*.yaml"))
                .filter(Resource::exists)
                .map(resource -> {
                    try {
                        return resource.getInputStream();
                    } catch (IOException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull);
    } catch (IOException e) {
        logger.error("Failed to get definitions from directory {}", path, e);
        return Stream.of();
    }
}
aksh1618
  • 2,245
  • 18
  • 37