17

我很困惑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. 我的意思是它是通过某些PATHs 还是以某种顺序工作工作?

如果是这样,如何配置getResourceAsStream()寻找的地方?

谢谢!

4

1 回答 1

20

当您调用时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");
于 2013-10-28T04:04:45.497 回答