java 如何从运行时类路径中读取目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12007012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a directory from the runtime classpath?
提问by IAmYourFaja
My Java application needs to be able to find a myconfig/
directory which will be bundled inside the same JAR:
我的 Java 应用程序需要能够找到myconfig/
将捆绑在同一个 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 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 filefrom the classpath doesn't work for directories:
我实际上如何myconfig/
从运行时类路径中读取此目录?我做了一些研究,似乎从类路径读取文件的正常方法不适用于目录:
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!
那么有谁知道如何从运行时类路径中读取整个目录(而不是单个文件)?提前致谢!
Please note: It is not possible to load the files individually, myconfig
is a directory with thousands of properties files inside it.
请注意:无法单独加载文件,这myconfig
是一个包含数千个属性文件的目录。
采纳答案by maba
You can use the PathMatchingResourcePatternResolver
provided by Spring.
您可以使用PathMatchingResourcePatternResolver
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.
我没有对返回的东西做任何花哨的事情,Resource
但你得到了图片。
Add this to your maven dependency (if using maven):
将此添加到您的 maven 依赖项(如果使用 maven):
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
回答by Kenster
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.
您可以调用ClassLoader.getResource()
以在目录(或目录本身,如果getResource()
将返回目录)中查找特定文件。getResource()
返回指向结果的 URL。然后,您可以将此 URL 转换为其他库需要的任何形式。
回答by Thorsten
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");