Java – how do I read directories from the runtime classpath?

My java application needs to be able to find a myconfig / directory that will be bundled in the same jar:

myjar.jar/
    com/
        me/
            myproject/
                ConfigLoader.java --> looks for myconfig/ directory and its contents
    myconfig/
        conf-1.xml
        conf.properties
        ... etc.

How do I read this myconfig / directory from the runtime classpath? I have done some research and it seems that the normal method of reading files from the classpath does not work for the directory:

InputStream stream = ConfigLoader.class.getResourceAsStream("myconfig");

So does anyone know how to read an entire directory (rather than a single file) from the runtime classpath? Thank you in advance!

Please note: the file cannot be loaded separately. Myconfig is a directory containing thousands of property files

Solution

You can use the pathmatchingresourcepratternresolver provided by spring

public class SpringResourceLoader {

    public static void main(String[] args) throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        // Ant-style path matching
        Resource[] resources = resolver.getResources("/myconfig/**");

        for (Resource resource : resources) {
            InputStream is = resource.getInputStream();
            ...
        }
    }
}

I didn't do anything about the returned resources, but you got the photos

Add it to your Maven dependency (if Maven is used):

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>