public final static String RUNTIME_HOME = System.getProperty("RUNTIME_HOME");
protected volatile boolean reload = false;
protected final String CONFIG_FILE;
protected final Properties prop = new Properties();
private static CBECConfigFile instance = new CBECConfigFile();
public static CBECConfigFile getInstance(){
return instance;
}
private CBECConfigFile(){
this(RUNTIME_HOME + "/config/" + "cbec-config.properties");
}
protected CBECConfigFile(String configFile){
CONFIG_FILE = configFile;
this.init();
}
/**
* 加载配置文件到内存中
*/
private void init() {
InputStream is = null;
try {
is = new FileInputStream(CONFIG_FILE);
prop.load(is);
} catch (IOException e) {
logger.error("加载配置文件异常:[" + CONFIG_FILE + "], " + e.getMessage(), e);
} finally {
if(is != null){
try {
is.close();
} catch (Exception e) {
}
}
}
}
/**
* 得到配置文件中属性的值
* @param key
* @return
*/
public String getValue(String key) {
if(reload){
synchronized (prop) {
if(reload){
init();
reload = false;
}
}
}
return prop.getProperty(key);
}
public String getValue(String key, String defaultValue) {
if(reload){
synchronized (prop) {
if(reload){
init();
reload = false;
}
}
}
return prop.getProperty(key, defaultValue);
}
/**
* 更改属性的值
* @param key
* @param value
* @param isSave, 是否保存到配置文件中
*/
public synchronized void setValue(String key, String value, boolean isSave) {
prop.setProperty(key, value);
if(isSave){
FileOutputStream os = null;
try {
os = new FileOutputStream(CONFIG_FILE);
prop.store(os, "");
} catch (IOException e) {
logger.error("修改配置文件异常:[" + CONFIG_FILE + "], " + e.getMessage(), e);
} finally {
if(os != null){
try {
os.close();
} catch (Exception e) {
}
}
}
}
}
/**
* 重新加载配置文件中所有属性
*/
public synchronized void reload(){
this.reload = true;;
}
以上代码中,以RUNTIME_HOME的参数方式,动态获取当前类运行的项目的路径,在eclipse的主类上右键配置运行在弹出的窗口中选择自变量tab页的VM自变量中设置
-DRUNTIME_HOME=${workspace_loc:cn.test}参数后,当类运行后就可以取到当前的绝对路径/cn.test目录。