Where does getResourceAsStream(file) search for th

2019-04-26 16:38发布

I've got confused by getResourceAsStream();

My package structure looks like:

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

And I want to read from floodlightdefault.properties. Here is my code, lying in the net.floodlightcontroller package:

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

But it failed, getting is == null. So I'm wondering how exactly does getResourceAsStream(file) search for the file. I mean does it work through certain PATHs or in a certain order?

If so, how to config the places that getResourceAsStream() looks for?

Thx!

标签: java class jvm
1条回答
Emotional °昔
2楼-- · 2019-04-26 17:08

When you call this.getClass().getClassLoader().getResourceAsStream(File), Java looks for the file in the same directory as the class indicated by 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");
查看更多
登录 后发表回答