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值,包含有空格的可能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章