How to read a directory from the runtime classpath?

后端 未结 3 1860
后悔当初
后悔当初 2021-01-04 08:51

My Java application needs to be able to find a myconfig/ directory which will be bundled inside the same JAR:

myjar.jar/
    com/
        me/
           


        
相关标签:
3条回答
  • 2021-01-04 09:08

    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.

    0 讨论(0)
  • 2021-01-04 09:23

    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");
    
    0 讨论(0)
  • 2021-01-04 09:25

    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>
    
    0 讨论(0)
提交回复
热议问题