Did you ever required a property or a config file to be read from Java? Each and every real time projects need to read some of the application specific configurations from a property file. It is always recommended to use a property file to have the values configured rather than hard coding it in your code. If the parameters are hard coded in the code, you will require a new version of the application to be created every time you need to change the parameters. To over come this the best way is to read configurations from a property file, and java allows this in a very simple way.
File file = new File("properties file absolute path");
if(file.exists) {
java.util.Properties prop = new java.util.Properties();
FileInputStream in = new FileInputStream(file);
prop.load(in);
if(prop != null) {
Iterator it = prop.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
String val = prop.getProperty(key);
System.out.println("Key : Value = " + key + " : " + value);
}
} else {
System.out.println("Property is null");
}
} else {
System.out.println("File not found");
}
The above code will read the config parameters from the property file in key-value pair. This can then be saved in a hashmap to retrieve the values.
No comments:
Post a Comment