Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all files in directory in the classpath

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.

like image 681
Bohemian Avatar asked Nov 18 '15 15:11

Bohemian


2 Answers

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.

like image 120
Andy Wilkinson Avatar answered Sep 19 '22 10:09

Andy Wilkinson


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();
    }
}
like image 28
aksh1618 Avatar answered Sep 23 '22 10:09

aksh1618