2014年4月21日 星期一

Java Project 讀取 config.properties 設定檔的方式

首先
        將設定檔的位置放至在/src下,接著在想要使用設定檔的java class內加上程式碼

private Properties props;

private void loadProperties() throws FileNotFoundException, IOException {
props = new Properties();
try {
InputStream inputStream =      this.getClass().getClassLoader().getResourceAsStream("config.properties");
props.load(inputStream);
//System.out.println("Get Config Properties Successful");
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}

}

private String getConfig(String key) {
return props.getProperty(key);
}

public ConfigTest() throws NamingException, SQLException, FileNotFoundException, IOException {
init();
}

private void init() throws FileNotFoundException, IOException {
loadProperties();
}


假設你的設定檔的內容可能為
test.Property = justTest (注意test後面有個點,其實也可以合在一起,只是特別註明此法可以用不同的符號區隔)

那麼接下來再你需要讀取設定檔的method裡(與剛才程式碼同個class)

String test = getConfig("test.Property");

則此時 test ="justTest"

此法的缺點是當別支class呼叫到些class時,每次都會重新讀取設定檔
但優點也可以說,我不需重新佈署程式,只單純修改程式設定檔參數即可執行新的參數。








沒有留言:

張貼留言