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 PATH
s or in a certain order?
If so, how to config the places that getResourceAsStream()
looks for?
Thx!
The java. lang. Class. getResourceAsStream() finds a resource with a given name.It returns a InputStream object or null if no resource with this name is found.
getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .
The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With