• Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassName.class.getResourceAsStream() throws exception  RSS feed

 
Ahsan Bagwan
Ranch Hand
Posts: 254
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have config.properties placed in src folder and subsequently available in bin folder. My attempt at loading the property throws Null Pointer exception.



This is the first few lines of stack trace,



However, invoking like

ClassName.class.getClassLoader().getResourceAsStream()

does the trick.

Is this the expected behaviour? If not, what fundamental understanding I need to have here?
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's really not much useful I can say without seeing something of an SSCCE. We don't even know the value of PROPERTIES_FILE.
 
Ahsan Bagwan
Ranch Hand
Posts: 254
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the class is like barring a few changes

 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I see the problem.

Read the description of Class.getResourceAsStream() *carefully*.
 
Ahsan Bagwan
Ranch Hand
Posts: 254
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Still not confident what the real reason is behind this behavior. Is it because the class has already been loaded? Does not prepending the file with a / does not resolve it to absolute path?

Please tell me if my questions sound gibberish.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You say you have src/config.properties. You're trying to load it through getResourceAsStream("config.properties"). The documentation says that this format will resolve to an absolute path of modified_package_name/name, or in your case, src/package/full/name/config.properties. This obviously doesn't match the location of your file. If you want to specify a path relative to the classpath, rather than the class, you should use a slash.
 
Ahsan Bagwan
Ranch Hand
Posts: 254
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can't thank you enough, Stephan. It was difficult to wrap my head around the property file path that is expanded . I was also mixing up absolute and relative path.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!