views:

521

answers:

3

Hi,

I have created a dynamic web project within Eclipse. I created a properties file inside the src directory:

<project-root>/src/props.properties

I'm starting Tomcat via Eclipse in debug mode. Now I want to read the properties file from one of my POJOs, but I get a FileNotFoundException. The current path seems to be the Eclipse path.

I had a look into the web for solution, but none of them worked for me. Maybe I did something wrong. The code is like this:

File file = new File("props.properties");
FileReader reader = new FileReader(file);
properties.load(reader);

How should I acces the properties file? Where should it be located?

Thanks in advance.

A: 

Check this question. You should do "src/props.properties"

Lombo
A: 

Is your project set to build automatically? If so (or you're building manually), check whetherprops.properties appears in your project's output folder (in Eclipse this is usually "bin" but may be WebRoot or something else, depending on how your project is set up).

When a project builds, it should copy over config files as well as your compiled classes, JSPs etc. However, I believe that file readers, by default, use the JVM's home directory for their source. In Eclipse's case, this means that your props.properties file would have to be in the project root, i.e. not the "src" folder.

Ben Poole
+1  A: 

If its a web application then the properties will get deployed to WEB-INF/classes and can be loaded using the class loader

InputStream in = getClass().getResourceAsStream("/props.properties");
properties.load(in);
in.close();

Actully that should work regardless of whether it is a webapp or not.

I'm assuming src is defined as a source folder

objects
Thanks all for answering. I forgot to mention that I'm starting tomcat via eclipse. The properties file is copied to: C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\WebAppName\WEB-INF\classes. Now I have a copy of the props file in the project root and in src folder, but I am not able to acces it anyway.
c0d3x
loading it as a resource as I showed above should work
objects
Where is your pojo class? The above assumes they are both loaded by the same classloader
objects
This is the way to go. It's better to load resources via a classloader to avoid dependencies on local file system arrangement, current working directory etc. The resource location has to be on the classpath of course, so WEB-INF/classes is a good place.BTW if you omit the slash - getResourceAsStream("props.properties") - the resource is expected in the same package as the current class.
Adriaan Koster