Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto access properties file from Java EE web application?

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.

like image 599
c0d3x Avatar asked Mar 02 '10 09:03

c0d3x


People also ask

How do I read properties file in Web INF?

Load Properties File from WEB-INF folder To be able to read a properties file stored under WEB-INF folder we will need to access ServletContext. We will do it by injecting the ServletContext into the Root Resource Class with the @Context annotation.

How do you read the data from a properties file in Java?

Core Java bootcamp program with Hands on practice Each key and its corresponding value in the property list is a string. The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load .


1 Answers

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 = {NameOfClassWhereThisisInvoked}.class.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

like image 165
objects Avatar answered Sep 18 '22 19:09

objects