Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does getResourceAsStream(file) search for the file?

Tags:

java

class

jvm

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!

like image 805
qweruiop Avatar asked Oct 24 '13 15:10

qweruiop


People also ask

When using class getResourceAsStream Where will the resource be searched?

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.

How do you get path from getResourceAsStream?

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 / .

What does getResourceAsStream do in Java?

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.


1 Answers

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");
like image 197
Nathaniel Jones Avatar answered Jan 04 '23 08:01

Nathaniel Jones