Java如何读取properties文件

文件结构:

projectname

---src/test/java

    -----packagename

---src

    ---config/config.properties  //文件内容为config=world

--lib

--bin/target

   -----classes

   -----test-classes

          ----config2/config2.properties // 文件内容为config2=hello

1. 通过getResourceAsStream()  getResource()

为什么可以从这个类对象中得到资源字节流呢?
可以这样理解:从一本书的对象中,你可以得到这本书的名字,也可以得到这本书到底有多少页。
书和书之间是不同的。
一个类对象和一个类对象也是不同,并且这些类位置必然是不同的,
getResourceAsStream:其本质是,根据类所在的位置,去加载配置文件所在的位置,

  Example:           

public static Properties p;

public static void setProperties(Properties tempP){
p = tempP;
}

public static void getProperties(){
System.out.println(TC_Operation.class.getResource("")); 
System.out.println(TC_Operation.class.getResource("/"));

InputStream inputStream = instance.getClass().getClassLoader().getResourceAsStream("config2/config2.properties"); //这里需要写testclasses后面的所有路径

Properties p1= new Properties();
 try{
 p1.load(inputStream);
 
 } catch(IOException e1){
 e1.printStackTrace();
 }
 setProperties(p1);
}

public static void main(String[ ]  args){

getProperties();

p1.p.getProperty("config2");

}

终端输出:

file:/E:/Documents/QA.Management/automation/swiftcoder/target/test-classes/

file:/E:/Documents/QA.Management/automation/swiftcoder/target/test-classes/swiftcoder/

hello

2. 通过ResourceBundle.getBundle

首先config/config.properties放在src下面,然后build properties->add lib path->add this config folder加入classpath

然后:

Example:

public static String getString(String key){
if(key== null || key.equals("") || key.equals("null")){
System.out.println(key +" is null!");
return "";
}
String result ="";
try{
result = resourceBundle.getString(key);
} catch(MissingResourceException e){
e.printStackTrace();
}
return result;
}

public static void main(Strings[ ] args){

propertyFileName="config";
resourceBundle = ResourceBundle.getBundle(propertyFileName);
    这里config.properties文件在引用,只需要写config,文件后缀名省略

getString("config");


}

控制输出:

world

注意的是,如果文件中,key值为该行光标结束处为一个key值,包含有空格的可能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值