Accessing a .properties file from a servlet

Hi,

I want to access offset.properties, located in tomat/webapps/MyApp/web-inf/classes from my servlet, also int the same directory, of course.

I tried using:

Properties offsetProperties = new Properties();

offsetProperties.load(new FileInputStream("offset.properties"));

but it threw a file not found exception....

Where do i have to put the .properties file, and what do i put in for the path, where i have "offset.preoperties" ?

Thanks alot for any help

X

ThePhatBarren.

[548 byte] By [TheBarren] at [2007-9-26 2:39:34]
# 1

You need to load the properties file from the classpath. Try:

InputStream is = getClass().getResourceAsStream("servlet.properties");

if (is != null)

{

Properties props = new Properties();

props.load(is);

}

If you do that, you can place the properties file anywhere in the classpath and have it load.

smiths at 2007-6-29 10:12:19 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Try not to associate the location of the class file a class was loaded from and the current directory - they are completely unrelated. Sometimes they happen to be the same (only when you execute the java command in the directory where unpackaged top-level classes reside), but the two concepts are different.

smiths at 2007-6-29 10:12:19 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

> > InputStream is = getClass().getResourceAsStream("servlet.properties");

>

BTW, the code posted above will load the properties file from the same package this class was loaded from. If your class is not in a package, the result will be the same. But say you have this setup:

WEB-INF/classes

- com

- mycorp

- package

- Servlet.class

Then the code above will access:

WEB-INF/classes

- com

- mycorp

- package

- servlet.properties

If you use:

InputStream is = getClass().getResourceAsStream("/servlet.properties");

Then it will look here:

WEB-INF/classes

- servlet.properties

BTW 2 - the search algorithm above is simplified for brevity. See the javadocs for the full algorithm.

smiths at 2007-6-29 10:12:19 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

Hey Thanks alot!

I have never used ther Class methods before.....

I was looking through it's API to try to find a similar way to get the FileOutputStream required to write to the properties after i modify it, but couldn't see a way... Can u help me there?

Thanks a million

TheBarren at 2007-6-29 10:12:19 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...