您的位置:首页 > 编程语言 > Java开发

java基础 —— properties 使用

2016-01-04 18:54 393 查看
目的:分别读取myPro*.properties文件内容,复习一下项目中读取资源配置文件的方法。

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

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



前提:使用 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") 参数只写资源文件名称即可。

如果你有更好的方法,请不吝赐教! ^_^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: