Reading a resource from the Classpath in Java

May 29, 2008

Today I found something that, although very subtle, helped me to get out weird behaviors.

I’m working in a Twitter API written in java and needed to load a configuration file from a package among my source code. So I tried with this.getClass().getResourceAsStream(filename) but wasn’t being able to get it, so I googled some about it and found something very interesting.
The code this.getClass().getResourceAsStream(filename) only looks for a file on the same directory of the .class file. To load a file that’s somewhere within the enrire classpath do this.getClass().getClassLoader().getResourceAsStream(filename).

When you stop a second and think about the first piece of code you see that this behavior is more logic than what you were expecting.

For those who don’t understand how did they do it take a look inside the code from the Class class.
The getResourceAsStream(String) method calls a resolveName(String) method that actually append to the string parameter the path of the class itself. So that’s why you only can load files from the .class directory.

Hopes it can help some one with the same doubts that I had.

Leave a comment