如何从运行时类路径中读取目录?

IAm*_*aja 12 java classpath

我的Java应用程序需要能够找到一个myconfig/将捆绑在同一个JAR中的目录:

myjar.jar/
    com/
        me/
            myproject/
                ConfigLoader.java --> looks for myconfig/ directory and its contents
    myconfig/
        conf-1.xml
        conf.properties
        ... etc.
Run Code Online (Sandbox Code Playgroud)

我如何实际myconfig/从运行时类路径中读取此目录?我做了一些研究,似乎从类路径中读取文件的常规方法对目录不起作用:

InputStream stream = ConfigLoader.class.getResourceAsStream("myconfig");
Run Code Online (Sandbox Code Playgroud)

那么有谁知道如何从运行时类路径(而不是单个文件)读取整个目录?提前致谢!

请注意:无法单独加载文件,myconfig是一个包含数千个属性文件的目录.

mab*_*aba 12

您可以使用PathMatchingResourcePatternResolverSpring提供的.

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();
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有对返回做任何事情,Resource但是你得到了照片.

将此添加到您的maven依赖项(如果使用maven):

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)


Ken*_*ter 5

您可以调用ClassLoader.getResource()以在目录(或目录本身,如果getResource()将返回目录)中查找特定文件。getResource()返回指向结果的URL。然后,您可以将该URL转换为其他库所需的任何形式。