Where does getResourceAsStream(file) search for th

2019-04-26 16:36发布

问题:

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!

回答1:

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");


标签: java class jvm