1、Properties从jar外或classPath读取配置文件value方法
调用:
String mailFrom= Common.readProperty("./config.properties","MAIL_FROM"); String passwd= Common.readProperty("./config.properties","MAIL_PASSWORD"); String mailTo= Common.readProperty("./config.properties","MAIL_TO");
方法:
/**
* 按key获取值
* @param filename 文件名
* @param key 键
* @return value
*/
public static String readProperty(String filename,String key){
Properties pros=new Properties();
String value="";
InputStream is=null;
try{
if (Common.isRunningInJar()) { //从jar包外.当前目录读取
String filePath = System.getProperty("user.dir") + "/" + filename;
is = new FileInputStream(filePath);
}
else {//非jar包,从classpath获取
String filePath = Common.class.getClassLoader().getResource(filename).getPath();
is = new FileInputStream(filePath);
}
InputStreamReader reader = new InputStreamReader(is,"UTF-8");
pros.load(reader);
value=pros.getProperty(key);
reader.close();
}
catch (IOException e){
log.error(String.valueOf(e));
}
finally {
try{
if(is != null) {
is.close();
}
}catch (IOException e){
log.error(e.toString());
}
}
return value;
}
判断是否是jar包执行方法:
调用:
if (Common.isRunningInJar()) { //从jar包外.当前目录读取
方法:
/**
* 是否以Jar包运行
* @return boolean true真或false假
*/
public static boolean isRunningInJar() {
try {
String className = Common.class.getName().replace('.', '/');
String classJar = Common.class.getResource("/" + className + ".class").toString();
return classJar.startsWith("jar:");
} catch (Exception e) {
log.warn("get Running status failed.");
return false;
}
}