How to read a properties file in a web application

Let’s consider that you have a war file named SampleApp.war which has a properties file named MyApp.properties at it’s root

SampleApp.war
   |- myApp.properties
   |- WEB-INF
     |- classes
       |- org
          |- myApp
          |- MyPropertiesReader.class


Here root folder in war is equivalent to Source Folder in Netbeans.
That means you have to keep your properties file in default package of your Source Files folder.
Let’s assume that you want to read the property named “abc” present in the properties file:


myApp.properties:

abc=some value
xyz=some other value

Let’s consider that the class org.myApp. MyPropertiesReader present in your application wants to read the property. Here’s the code for the same:

package org.myapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyPropertiesReader {

    public MyPropertiesReader() {
    }

    public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }
}

Now suppose the properties file is not at the root of the application, but inside a folder (let’s name it config) in the web application, something like:

SampleApp.war
   |- config
    |- myApp.properties   
   |- WEB-INF
    |- classes
      |- org
         |- myApp
           |- MyPropertiesReader.class

There will just be one line change in the above code:

public void doSomeOperation() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("config/myApp.properties");
        Properties properties = new Properties();
        System.out.println("InputStream is: " + inputStream);
        properties.load(inputStream);
        String propValue = properties.getProperty("abc");
        System.out.println("Property value is: " + propValue);
    }

 

Source