如何从运行时类路径读取目录? [英] How to read a directory from the runtime classpath?
问题描述
我的Java应用程序需要能够找到 myconfig /
目录,该目录将捆绑在同一JAR中:
My Java application needs to be able to find a myconfig/
directory which will be bundled inside the same JAR:
myjar.jar/
com/
me/
myproject/
ConfigLoader.java --> looks for myconfig/ directory and its contents
myconfig/
conf-1.xml
conf.properties
... etc.
实际上如何从运行时类路径中读取此 myconfig /
目录?我已经做过一些研究,看来从类路径读取文件的常规方法不适用于目录:
How do I actually go about reading this myconfig/
directory off the runtime classpath? I've done some research and it seems that the normal method of reading a file from the classpath doesn't work for directories:
InputStream stream = ConfigLoader.class.getResourceAsStream("myconfig");
所以没有人知道如何从运行时类路径读取整个目录(而不是单个文件) )?
So does anyone know how to read an entire directory from the runtime classpath (as opposed to a single file)? Thanks in advance!
请注意:无法单独加载文件, myconfig
是一个包含以下内容的目录
Please note: It is not possible to load the files individually, myconfig
is a directory with thousands of properties files inside it.
推荐答案
您可以使用 PathMatchingResourcePatternResolver
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.
将此添加到您的maven依赖关系(如果使用maven):
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>
这篇关于如何从运行时类路径读取目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!