18

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!

qweruiop
  • 3,156
  • 6
  • 31
  • 55
  • Do you have added the resources directory in a classpath when running your code? Generally speaking, the behavior of getResourceAsStream depends on the ClassLoader implementation. – Stanislav Mamontov Oct 24 '13 at 15:49
  • Generally speaking it will also depend on what `this` refers to. – Radiodef Oct 24 '13 at 15:55
  • To fix your null problem, there are two things I see initially. First, it looks like you just need to change your directory to `"resources/floodlightdefault.properties"`. Second, the method could be looking for the resource inside your build directory and the directory structure you've shown appears to be the IDE project's source folder. Though of course if you've added the resources to the project, the IDE ought to copy the files to the build directory automatically. In a quick test with Netbeans, my resources only come up null if I remove them from _both_ the build and the src folder. – Radiodef Oct 24 '13 at 16:06
  • How are you building your project? Where does floodlightdefault.properties end up at run time? – artbristol Oct 24 '13 at 16:11

1 Answers1

22

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");
Nathaniel Jones
  • 1,829
  • 3
  • 29
  • 27