加載WEB-INF下的配置文件的工具類


public class PropertiesUtil {

static Logger logger = Logger.getLogger(PropertiesUtil.class);
private Properties properties;
public PropertiesUtil(String filename) {
String projectPath = getSystemRealPath();
String filepath = projectPath + File.separator + filename;
try {
if(StrUtil.isNull(filename) || !filename.endsWith(".properties")){
throw new Exception("必須是.properties的文件類型!");
}
FileInputStream fi = new FileInputStream(filepath);
properties = new Properties();
properties.load(fi);//載入配置文件
fi.close();
} catch (Exception e) {
logger.error("載入配置文件:["+filepath+"]出錯了!", e);
}
}
public String getValue(String key) {
return properties != null ? properties.getProperty(key, "") : "";
}
/**
* 獲取系統實際路徑
* @return
*/
private static String getSystemRealPath() {
Class theClass = PropertiesUtil.class;
java.net.URL u = theClass.getProtectionDomain().getCodeSource().getLocation();
String str = u.toString(); //得到這個函數所在類的路徑
str = str.substring((str.startsWith("jar") ? 9 : 6), str.length()); //截去一些前面6個無用的字符
str = str.replaceAll("%20", " "); //將%20換成空格(如果文件夾的名稱帶有空格的話,會在取得的字符串上變成%20)
str = str.substring(0, str.indexOf("WEB-INF")); //截取到“WEB-INF”在該字符串的位置
if (System.getProperty("os.name").toUpperCase().indexOf("LINUX") >= 0) {
str = "/" + str;
}
return str;
}
}


假設有個配置文件爲test.properties,裏面的內容爲:
username = test
passwrod = test

則在類中調用該工具類的方法爲:
PropertiesUtil p = new PropertiesUtil("/WEB-INF/test.properties");
String service_url=p.getValue("username");


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