How to read a directory from the runtime classpath?

半城伤御伤魂 提交于 2019-11-30 17:47:24

You can use the PathMatchingResourcePatternResolver 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 fancy with the returned Resource but you get the picture.

Add this to your maven dependency (if using maven):

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

You could call ClassLoader.getResource() to find a particular file in the directory (or the directory itself, if getResource() will return directories). getResource() returns a URL pointing to the result. You could then convert this URL into whatever form the other library requires.

The trick seems to be that the class loader can find directories in the classpath, while the class can not.

So this works

this.getClass().getClassLoader().getResource("com/example/foo/myconfig");

while this does not

this.getClass().getResource("myconfig");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!