Property File Reader: This is an util class which can be used to convert the properties file with key and value pairs to HashMap. The passed key to getMapForPropertiesFileKey must de already defined as system variable in operating system. This is having only one static method and returns HashMap of key value pairs.
To define a system variable in WINDOWS go to My Computer - Properties - Advanced - Environment Variable - System Variables then click on New and define variable name as key which will be passed to the getMapForPropertiesFileKey method and value as the absolute path of the properties file.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertyReader {
public static Map<String, String> getMapForPropertiesFileKey(
String propertyFileKey) throws Exception {
if (propertyFileKey == null || "".equals(propertyFileKey.trim())) {
throw new IllegalArgumentException("Invalid property file key name");
}
Map<String, String> envMap = System.getenv();
Map<String, String> proMap = null;
File file = null;
String proFileName = envMap.get(propertyFileKey);
if (proFileName == null || "".equals(proFileName)) {
throw new IllegalArgumentException(
"Property key not set in environment variable");
}
file = new File(proFileName);
if (!file.exists()) {
throw new IllegalArgumentException("Properties File not found "
+ file.getAbsolutePath());
}
Properties pro = new Properties();
InputStream is = new FileInputStream(proFileName);
pro.load(is);
is.close();
if (pro.size() > 0) {
proMap = new HashMap<String, String>(pro.size());
Set<String> keys = pro.stringPropertyNames();
for (String key : keys) {
if (null != pro.getProperty(key)
&& !"".equals(pro.getProperty(key).trim())) {
proMap.put(key, pro.getProperty(key));
}
}
}
return proMap;
}
}
No comments:
Post a Comment