加载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");


你可能感兴趣的:(Java)