The code to do this is pretty simple. 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
Let's assume that you want to read the property named abc
present in the properties file:
in myApp.properties
:
abc = someValue;
xyz = someOtherValue;
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;
/**
* Simple class meant to read a properties file
*
* @author Sudarsan Padhy
*
*/
public class MyPropertiesReader {
/**
* Default Constructor
*
*/
public MyPropertiesReader() {
}
/**
* Some Method
*
* @throws IOException
*
*/
public void doSomeOperation() throws IOException {
// Get the inputStream
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("myApp.properties");
Properties properties = new Properties();
System.out.println("InputStream is: " + inputStream);
// load the inputStream using the Properties
properties.load(inputStream);
// get the value of the property
String propValue = properties.getProperty("abc");
System.out.println("Property value is: " + propValue);
}
}