java加载配置文件

现在好多配置都放在了属性文件里,由java程序调用,一般讲java的配置文件放在web-info下程序里面获取路径 通过如下方式:

1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:/eclipseM9/workspace/tree/
tree是我web项目的根目录
 
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
获取上级目录的路径:

this.getClass().getClassLoader().getResource("../").getPath():

这个获取的是WEB-INO的目录全路径
 
这个方法也可以不在web环境里确定路径,比较好用
 
3.request.getContextPath();
获得web根的上下文环境

 

加载属性文件用到的是Apache的开源组件需要如下3个jar包:commons-configuration.jar  commons-lang-2.5.jar commons-collections-3.2.jar

程序如下:


   String str = this.getClass().getClassLoader().getResource("../")
     .getPath();
   Configuration config = new PropertiesConfiguration(str
     + "/config.properties");
   u2_contype = config.getString("u2.contype");
   u2_url = config.getString("u2.url");
   u2_username = config.getString("u2.username");
   u2_password = config.getString("u2.password");
   ms_contype = config.getProperty("ms.contype").toString();
   ms_username = config.getString("ms.username");
   ms_password = config.getString("ms.password");
   ms_url = config.getString("ms.url");
   debug = config.getInt("debug");

 

 

API:http://commons.apache.org/collections/api/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值