Java – Loading a properties file from Java package


I need to read a properties files that's buried in my package structure in

I've tried everything and I can't figure it out.

In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to work in both.

Best Solution

When loading the Properties from a Class in the package you can use

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("");

(Add all the necessary exception handling).

If your class is not in that package, you need to aquire the InputStream slightly differently:

InputStream in = 

Relative paths (those without a leading '/') in getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.

Using java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file /java/lang/String/foo.txt on the classpath.

Using an absolute path (one that starts with '/') means that the current package is ignored.