繁体   English   中英

getResourceAsStream(file)在哪里搜索文件?

[英]Where does getResourceAsStream(file) search for the file?

我对getResourceAsStream()感到困惑;

我的包结构如下:

\src
|__ net.floodlightcontroller // invoked getResourceAsStream() here
|__ ...
|__ resources
    |__ floodlightdefault.properties //target
    |__ ...

我想从floodlightdefault.properties中读取。 这是我的代码,位于net.floodlightcontroller包中:

package net.floodlightcontroller.core.module;
// ...
InputStream is = this.getClass().getClassLoader()
                 .getResourceAsStream("floodlightdefault.properties");

但它失败了,得到的is == null 所以我想知道getResourceAsStream(file)究竟是如何搜索file 我的意思是它通过某些PATH或按特定顺序工作吗?

如果是这样,如何配置getResourceAsStream()查找的位置?

谢谢!

当您调用this.getClass().getClassLoader().getResourceAsStream(File) ,Java会在与this指示的类相同的目录中查找该文件。 因此,如果您的文件结构是:

\src
|__ net.floodlightcontroller.core.module
    |__ Foo.java
|__ ...
|__ resources
    |__ floodlightdefault.properties //target
    |__ ...

然后你会打电话给:

InputStream is = Foo.class.getClassLoader()
             .getResourceAsStream("..\..\..\resources\floodlightdefault.properties");

更好的是,将包结构更改为:

\src
|__ net.floodlightcontroller.core.module
    |__ Foo.java
    |__ floodlightdefault.properties //target
    |__ ...

并致电:

InputStream is = Foo.class.getClassLoader()
             .getResourceAsStream("floodlightdefault.properties");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM