2014年4月21日 星期一

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

此法是採用 commons-configuration-1.x.jar (apache的OpenSource可以download)所提供的API
還需要commons-lang-2.x.jar

首先一樣把參數設定檔config.properties放在/src下
之後建立一個Class取名為 Constants,內容如下

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class Constants {

private final static String test_property;

static {
PropertiesConfiguration configuration = null;
try {
configuration = new PropertiesConfiguration("config.properties");
} catch(ConfigurationException e) {
e.printStackTrace();
System.out.println(e.getMessages());
}

test_property = configuration.getString("test_property");

}

public String getConfig(){
return test_property;
}

假設您的設定檔(.properties)內容為
test_property = this is a test

如果利用Constants Class來取得您要的設定檔內容呢!?如下

首先建立一個 ConfigTest.java

將剛才建立的Constants import進來(假設在同個package則不必)

接著

Contants cons = new Contants();

String test = cons.getConfig();

則此時 test 已經等於了 "this is a test"


此法的好處在於設定檔所有的內容都可經由Constants Class來取得
不需像上個方法一樣冗長的程式碼一一初始化


缺點是 修改參數後必須重新佈署程式,而且在 config.properties中

前面的 property key 不可含有 . 沒錯 就是點(上個範例可以)
而且等號後面的 key value不可有 , 沒錯就是逗號

以上面 test_property = this is a test 來說不可改為

test.property = this , is a test
這就2個錯誤都有了,其實第一個錯誤是 java String 類別不給使用
而第二個錯誤是 apache 會把逗號判斷成停止點,所以只能抓到 this 後面的字串就抓不到了




沒有留言:

張貼留言