Wednesday, September 16, 2009

Loading a Properties File in a Java Application

Most of the examples I found only rely on servletContext, but this is no use if you aren't using a servlet. Also, there is a quick approach using ResourceBundle, but that approach is limited in how you can load the properties file.

Properties tempProps = new Properties();
try {
URL startupPropsURL = this.getClass().getClassLoader().getResource("/test.properties");
File startupPropsFl = new File(startupPropsURL.toURI());

try {
InputStreamReader aRdr = new InputStreamReader(new FileInputStream(startupPropsFl));
tempProps.load(aRdr);
aRdr.close();
} catch (Throwable e) {
System.out.println("Error occured while trying to load test.properties ");
e.printStackTrace();
}

System.out.println("Getting log files from "+tempProps.getProperty("foo.baseURL"));
return tempProps.getProperty("foo.baseURL");
} catch (Throwable ex) {
System.out.println("Error occured while trying to read from log.properties ");
ex.printStackTrace();
}

Labels

Blog Archive

Contributors