How to get all files in directory in the classpath

15,719

Solution 1

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.

Solution 2

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();
    }
}
Share:
15,719
Bohemian
Author by

Bohemian

Self-proclaimed SQL guru, Java pro and regex fan... and currently elected moderator. In all code, I strive for brevity (without loss of legibility). The less code there is, the less places there are for bugs to lurk. While contributing here, I have learned that say not that you know something until you try to teach it. My real name is Glen Edmonds. If one of my posts "changed your life", you can donate to my Liberapay account. FYI, that cute animal I use for my avatar is a wombat.

Updated on June 08, 2022

Comments

  • Bohemian
    Bohemian almost 2 years

    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
    Bohemian over 8 years
    OK, but I don't know what I will find there. Perhaps "/mydir/*" with your code. I ended up getting it working with a PathMatchingResourcePatternResolver
  • bytor99999
    bytor99999 over 7 years
    What it the package for Resources? I could not find any class with that name that is part of Spring.
  • Andy Wilkinson
    Andy Wilkinson over 7 years
    Sorry, that was a typo in the answer. I've fixed it now.