tags:

views:

6677

answers:

3

I need to read a properties files that's buried in my package structure. 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. I can't figure it out. Please Help. Thank you.

+6  A: 

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.

Joachim Sauer
i guess the second snippet is the answer to the question..
Satya
Suggestion: Add an explanation when to use relative and when to use absolute paths (with and without the "/" at the beginning).
Aaron Digulla
I tried to give some explanation.
Joachim Sauer
A: 

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

Chris Kimpton
A: 

To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:

static {
    Properties prop = new Properties();
    InputStream in = CurrentClassName.class.getClass().getResourceAsStream("foo.properties");
    prop.load(in);
    in.close()
}

(Exception handling elided, as before.)

cobra libre