Wednesday, September 14, 2011

Java resources (.properties)

Ok so I am making progress on a fiddle project that I am working on. I decided I was going to store the the persistence unit name in a properties file to prevent embedding strings in the instantiation methods.

 

I sat and fought for sometime trying to get the resources as a stream and came across some interesting links that explain how to do this. Namely:

http://www.bartbusschots.ie/blog/?p=360

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemClassLoader%28%29

http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29

 

After fiddling and fiddling and getting very frustrated with the NullPointerException that kept on happening I was just about to give up.

 

Then I realised something. Looking at all the examples there is something I had added that I shouldn’t have

//Spot the ERROR!
Properties configFile = new Properties();
configFile.load(ClassLoader.getSystemResourceAsStream("/za/co/codeshark/application.properties"));


 



Don’t feel bad if you don’t see the problem. Laugh at me if you do Winking smile So here is the problem. If you have a look at the string pointing to the resource it has a leading “/”. Yes, this makes the path unresolvable. So it should have look like:



Properties configFile = new Properties();
configFile.load(ClassLoader.getSystemResourceAsStream("za/co/codeshark/application.properties"));


 



Notice that there is no leading “/”. Once I made this change everything started grooving and I was able to access my resource file. Once again kicking myself for not keeping these skills fresh. I find it weird though, that with all the examples of how to do this, none point out anything about how to resolve the path. Perhaps I am just over tired but I figured it might be good to make a note of this for 50 years from now!

No comments:

Post a Comment