Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Sunday, October 14, 2007

Reading from a property file in a web application without servlet context

Sometimes, there is a requirement for reading a file like a property file containing database connection setting or some other required information which you dont want to hard code in the java class. If servlet context is available then it can be done using <>.getContext() method or using getRealPath().

In case ServletContext is not available you can use the following code:

final URL url = this.getClass().getResource("DbSettings.properties");
private Properties p;
try {
p = new Properties();
InputStream stream = new FileInputStream(url.getFile());
p.load(stream);
String prop1 = p.getProperty("property1");
stream.close();
} catch (Exception e) {
System.out.println("E :: " + e.getMessage());
}


In the above code, DbSettings.properties is the file name place in the same path where the java class containing this code is located. property1 is the name of the property you want to read from the file. You can define a property file as name-value pair as follows:
property1=value1
property2=value2
... and so on

Please note that the values should be specified without single or double quotes.

Post a Comment