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.
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
.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With