文件结构:
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值,包含有空格的可能。