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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值