Loading a properties file from Java package

SacramentoJoe picture SacramentoJoe · Dec 2, 2008 · Viewed 317.4k times · Source

I need to read a properties files that's buried in my package structure in com.al.common.email.templates.

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.

Answer

Joachim Sauer picture Joachim Sauer · Dec 2, 2008

When loading the Properties from a Class in the package com.al.common.email.templates you can use

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();

(Add all the necessary exception handling).

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

InputStream in = 
 getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");

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.