将相对目录添加到 java 类路径并使用 ClassLoader().getResourceAsStream("")
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/842538/
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
adding relative directory to java classpath and using ClassLoader().getResourceAsStream("")
提问by sal
Is it possible to add a relative directory (ie, foo/bar/plugh) to the java classpath and use
是否可以将相对目录(即 foo/bar/plugh)添加到 java 类路径并使用
InputStream in = getClassLoader().getResourceAsStream("xyzzy.properties");
To fetch foo/bar/plugh/xyzzy.properties?
获取 foo/bar/plugh/xyzzy.properties?
My classpath looks like this:
我的类路径如下所示:
foo.jar;foo/bar/plugh;xyz.jar
And I am able to use classes and resources from both foo and xyz jars but not from the plugh directory. In those cases, inis always null.
而且我可以使用 foo 和 xyz jar 中的类和资源,但不能使用 plugh 目录中的类和资源。在这些情况下,in始终为空。
I can't get this to work and am not sure if this is just unsupported, I am missing something subtle or if I'm doing something wrong. Do I need to use an absolute path?
我无法让它工作,并且不确定这是否只是不受支持,我错过了一些微妙的东西或者我做错了什么。我需要使用绝对路径吗?
回答by Alex Beardsley
Maybe I'm misunderstanding what you're trying to do, but if you have a folder in your classpath, that means all the files underneath it should be in the classpath as well. If not, you can always pass each .properties file on the class path.
也许我误解了你想要做什么,但是如果你的类路径中有一个文件夹,这意味着它下面的所有文件也应该在类路径中。如果没有,您始终可以在类路径上传递每个 .properties 文件。
But either way, since the file/folder that contains the file is in the classpath, you should just be able to do:
但无论哪种方式,由于包含该文件的文件/文件夹位于类路径中,您应该能够执行以下操作:
InputStream in = new FileInputStream("classpath:xyz.properties")
And since "foo/bar/plugh" is in the classpath, one of the places it will look for xyz.properties is in "foo/bar/plugh".
并且由于“foo/bar/plugh”在类路径中,因此它将查找 xyz.properties 的位置之一在“foo/bar/plugh”中。

