读取Properties配置文件
2016-05-04 11:55
411 查看
通过读取properties文件获取配置项的值在开发中是很常用的,这种方式降低了变量和代码间的耦合,使得非开发人员也可以很容易的对系统的一些配置进行修改,比如配置数据库连接参数等。
之前一直使用下面的方式来获取properties中的属性值,大家可以很明显的看出来两种方式的区别:前一种方案能有效减少prop对象的生成,有点类似线程池,如果“池子”里已经存在prop对象,则直接读取即可。当然虽然这种方式能有效减少访问prop文件的时间,但是维持Map中的内容要比第二种方案耗费更多的资源。
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);
相关文章推荐
- Linux下rz/sz安装及使用方法
- Linux下安装MySQL 5.7
- Linux makefile 教程 非常详细,且易懂
- Runtime方法的使用—Method、Ivar、Property篇
- 【转载】shell编程——if语句 if -z -n -f -eq -ne -lt
- linux下的单实例进程 - 一个进程不能重复启动
- 使用Apache Bench进行压力测试
- Linux 系统常用命令汇总(一) 文件和目录操作
- 使用opencv的SVM实现车牌区域识别
- The Apache Axis2 Web service runtime in Tomcat v6.0 Server does not support the service project
- linux(centos)搭建SVN服务器
- maven+eclipse+tomcat配置过程记录
- Linux命令随记之chmod命令
- shell 去除 ^M
- Opencv人脸识别备忘
- Linux下LDAP统一认证解决方案
- Titan‘s storage backends Hbase open execption
- AS400 op
- ANMPP 12已经发布,安卓上的php环境 - Android NGINX MYSQL PGSQL PHP-FPM
- PhotoShop CS6 官方简体中文正式版原版+破解补丁下载