package com.newer;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
/**
* 動態讀取properties檔案類
* @author RSun
* @Date 2012-11-14下午03:18:17
*/
public final class ReadPropertiesFile {
/** 屬性檔案全名,需要的時候請重新設定PFILE **/
private static String PFILE = "test.properties"; // src下面的檔案
/** 屬性檔案所對應的屬性物件變數 **/
private long m_lastModifiedTime = 0;
/** 對應於屬性檔案的檔案物件變數 **/
private File m_file = null;
/** 屬性檔案所對應的屬性物件變數 **/
private Properties m_props = null;
/** 唯一執行個體 **/
private static ReadPropertiesFile m_instance = new ReadPropertiesFile();
/** 私人建構函式 **/
private ReadPropertiesFile() {
try {
m_lastModifiedTime = getFile().lastModified();
if (m_lastModifiedTime == 0) {
System.err.println(PFILE + "file does not exist!");
}
m_props = new Properties();
m_props.load(new FileInputStream(getFile()));
} catch (URISyntaxException e) {
System.err.println(PFILE + "檔案路徑不正確");
e.printStackTrace();
} catch (Exception e) {
System.err.println(PFILE + "檔案讀取異常");
e.printStackTrace();
}
}
/**
* 尋找ClassPath路徑擷取檔案
* @return File對象
* @throws URISyntaxException
*/
private File getFile() throws URISyntaxException {
URI fileUri = this.getClass().getClassLoader().getResource(PFILE).toURI();
m_file = new File(fileUri);
return m_file;
}
/**
* 靜態Factory 方法
* @return 返回ConfigurationRead的單一執行個體
*/
public synchronized static ReadPropertiesFile getInstance() {
return m_instance;
}
/**
* 讀取一特定的屬性項
* @param name 屬性項的名稱
* @param defaultVal 讀取失敗預設值
* @return
*/
public String getConfigItem(String name, String defaultVal) {
long newTime = m_file.lastModified();
// 檢查屬性檔案是否被修改
if (newTime == 0) {
// 屬性檔案不存在
if (m_lastModifiedTime == 0) {
System.err.println(PFILE + " file does not exist!");
} else {
System.err.println(PFILE + " file was deleted!!");
}
return defaultVal;
} else if (newTime > m_lastModifiedTime) {
m_props.clear();
try {
m_props.load(new FileInputStream(getFile()));
} catch (Exception e) {
System.err.println("檔案重新讀取異常");
e.printStackTrace();
}
}
m_lastModifiedTime = newTime;
String val = m_props.getProperty(name);
if (val == null) {
return defaultVal;
} else {
return val;
}
}
/**
* 讀取一特定的屬性項
* @param name 屬性項的項名
* @return 屬性項的值(如此項存在), 空(如此項不存在)
*/
public String getConfigItem(String name) {
return getConfigItem(name, "");
}
/**
* 讀取一特定的屬性項
* @param name 屬性項的名稱
* @return 截取空格後的數值
*/
public String getConfigItemTrim(String name) {
return getConfigItem(name, "").trim();
}
// 測試
public static void main(String[] args) {
System.out.println(ReadPropertiesFile.getInstance().getConfigItemTrim("aaa"));
System.out.println(ReadPropertiesFile.getInstance().getConfigItemTrim("bbb"));
System.out.println(ReadPropertiesFile.getInstance().getConfigItem("ccc", "哈哈,你被忽悠了。"));
}
}