[英]Where does getResourceAsStream(file) search for the file?
I've got confused by getResourceAsStream()
; 我对
getResourceAsStream()
感到困惑;
My package structure looks like: 我的包结构如下:
\src
|__ net.floodlightcontroller // invoked getResourceAsStream() here
|__ ...
|__ resources
|__ floodlightdefault.properties //target
|__ ...
And I want to read from floodlightdefault.properties. 我想从floodlightdefault.properties中读取。 Here is my code, lying in the
net.floodlightcontroller
package: 这是我的代码,位于
net.floodlightcontroller
包中:
package net.floodlightcontroller.core.module;
// ...
InputStream is = this.getClass().getClassLoader()
.getResourceAsStream("floodlightdefault.properties");
But it failed, getting is == null
. 但它失败了,得到的
is == null
。 So I'm wondering how exactly does getResourceAsStream(file)
search for the file
. 所以我想知道
getResourceAsStream(file)
究竟是如何搜索file
。 I mean does it work through certain PATH
s or in a certain order ? 我的意思是它通过某些
PATH
或按特定顺序工作吗?
If so, how to config the places that getResourceAsStream()
looks for? 如果是这样,如何配置
getResourceAsStream()
查找的位置?
Thx! 谢谢!
When you call this.getClass().getClassLoader().getResourceAsStream(File)
, Java looks for the file in the same directory as the class indicated by this
. 当您调用
this.getClass().getClassLoader().getResourceAsStream(File)
,Java会在与this
指示的类相同的目录中查找该文件。 So if your file structure is: 因此,如果您的文件结构是:
\src
|__ net.floodlightcontroller.core.module
|__ Foo.java
|__ ...
|__ resources
|__ floodlightdefault.properties //target
|__ ...
Then you'll want to call: 然后你会打电话给:
InputStream is = Foo.class.getClassLoader()
.getResourceAsStream("..\..\..\resources\floodlightdefault.properties");
Better yet, change your package structure to look like: 更好的是,将包结构更改为:
\src
|__ net.floodlightcontroller.core.module
|__ Foo.java
|__ floodlightdefault.properties //target
|__ ...
And just call: 并致电:
InputStream is = Foo.class.getClassLoader()
.getResourceAsStream("floodlightdefault.properties");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.