properties java_java基础 —— properties 使用

目的:分别读取myPro*.properties文件内容,复习一下项目中读取资源配置文件的方法。

项目下载地址:http://pan.baidu.com/s/1jHuzPxs

项目结构如图,ReadProperties.java为读取资源文件主要方法,:

88c116a3dfc3aa7b3f9a085826f1704d.png

前提:使用 InputStream 进行读取时,需注意关闭流!!

相同代码部分:

Properties prop=new Properties();

InputStream ins=null;

try{

ins....... // 代码变更部分

prop.load(ins);

String resultStr=prop.getProperty("param1");

}catch(Exception e){

e.printStackTrace();

}finally{

if(null!=ins){

try{

ins.close();

}catch(IOException e){

e.printStackTrace();

}

}

}

代码变更部分:

1、读取myPro1.properties,读取和类文件同一目录下的资源文件:

ins=ReadProperties.class.getResourceAsStream("myPro1.properties");// 不用 getClassLoader() 来获取getResourceAsStream(),这是获取同一路径下的资源文件

2、读取myPro2.properties,读取另一文件夹下的资源文件:

ins=ReadProperties.class.getClassLoader().getResourceAsStream("config/myPro2.properties");// 写资源文件所在的路径

3、读取myPro3.properties,读取src根目录下的资源文件:

ins=ReadProperties.class.getClassLoader().getResourceAsStream("myPro3.properties");// 只写资源文件名称即可

4、读取myPro4.properties,读取另一资源包下的资源文件

ins=ReadProperties.class.getClassLoader().getResourceAsStream("myPro4.properties");//  只写文件名即可;如果是configFolder/myPro4.properties,则报null异常

5、读取myPro5.properties,读取另一包下的资源文件

ins=ReadProperties.class.getClassLoader().getResourceAsStream("com/test/myPro5.properties"); // 资源文件所在路径,如果只写资源文件名称,报null异常

总结:

1、获取和类文件处于相同路径下的资源文件使用 ReadProperties.class.getResourceAsStream("myPro1.properties")来获取,不用.class.getClassLoader()

2、获取其它包或不同包下的文件夹下的配置文件,使用ReadProperties.class.getClassLoader().getResourceAsStream("config/myPro2.properties")来获取,参数是该资源文件所在的相对路径

3、获取src根目录或另一资源文件夹的根目录下的资源文件,使用ReadProperties.class.getClassLoader().getResourceAsStream("myPro2.properties")  参数只写资源文件名称即可。

如果你有更好的方法,请不吝赐教!   ^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值