Thursday, September 25, 2008

Reading value from Properties File

This method shows you how to read value from the properties file from java. We need to read some parameter from the properties file in order to allow user to customize the functionalities such as socket host and port number, user define error message, UI messages and so on.

You may have a singleton class to handle the specific properties file and have the public method to get the value by the key.

public String readFromProperties(String filePath, String keyName) {
Properties properties;
String value = null;
try {

properties = new Properties();
FileInputStream fis = new FileInputStream(filePath);
if (fis != null) {
properties.load(fis);
value = properties.getProperty(keyName);
fis.close();
}
} catch (FileNotFoundException e) {
// handle if file not found
} catch (IOException e) {
// handle reading properties files errors
}
return value;
}

No comments: