This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Make getResourceAsStream() work.  RSS feed

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The file exists, but InputStream is is always null. Why? Thanks.
String s = "C:/java/proddata/conf/tool.properties";
try {
InputStream is = Testpad.class.getResourceAsStream(s);
} catch (Exception e) {
System.out.println("error " + e);
}
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bruce,
getResourceAsStream() loads the file via Classloader and class loader tries to load it from the current CLASSPATH. So, if your folder,
C:/java/proddata/conf/
is in CLASSPATH then it will work. Otherwise not.
Regards
Maulin
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that the method uses the CLASSPATH is irrelevant, I think, since Bruce is specifying an absolute path. What is important here is that the API for getResourceAsStream() clearly states that, since the path does not begin with '/', the method will prepend the package name (substituting '/' for '.') for the class you're using. So if Testpad is in the package foo.bar, the system is now looking for the resource
foo/bar/C:/java/proddata/conf/tool.properties
somewhere in the classpath. Clearly, this is nonsense; we don't want the package name prepended like that. The getResourceAsStream() method is designed to make it easy to find resources located in the same directory as the class file associated with the class; it's not so great for other stuff. One simple possibility is to ditch the C: and search for
/java/proddata/conf/tool.properties
This should work if your call files are already on the C: drive, so / will get you to the root of that drive. Or more generally, use ClassLoader.getSystemResource(), which is a static method that does not try to associate itself with any particular class. Should be exactly what you need here.
 
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!