您的位置:首页 > 运维架构

读取Properties配置文件

2016-05-04 11:55 411 查看
通过读取properties文件获取配置项的值在开发中是很常用的,这种方式降低了变量和代码间的耦合,使得非开发人员也可以很容易的对系统的一些配置进行修改,比如配置数据库连接参数等。

public class PropertiesUtils {

private static Map<String, Properties> propertiesMap = new HashMap<String, Properties>();

public static String getPropertiesValue(String propertiesName, String key) {
InputStream in = null;
String obj = null;
try {
Properties prop = null;
if (!propertiesMap.containsKey(propertiesName)) {
prop = new Properties();
in = PropertiesUtils.class.getClassLoader()
.getResourceAsStream("/props/" + propertiesName);
prop.load(in);
propertiesMap.put(propertiesName, prop);
}
obj = propertiesMap.get(propertiesName).getProperty(key).trim();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return obj;
}
}


之前一直使用下面的方式来获取properties中的属性值,大家可以很明显的看出来两种方式的区别:前一种方案能有效减少prop对象的生成,有点类似线程池,如果“池子”里已经存在prop对象,则直接读取即可。当然虽然这种方式能有效减少访问prop文件的时间,但是维持Map中的内容要比第二种方案耗费更多的资源。

Properties props = new Properties();
try {
props.load(PropConnectionUtils.class.getClassLoader().getR esourceAsStream(propFiles));
} catch (IOException e) {
e.printStackTrace();
}
return props.getProperty(key);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: