您的位置:首页 > 运维架构

JDBC使用反射读取properties文件方法笔记

2016-07-15 10:33 519 查看
1,配置文件放到src下  

2,代码片段

public class CMConstant {
public static String getConfigureParameterFromJDBC(String paramString) {
String str = CMConstant.getRootPath() + File.separator + "WEB-INF"
+ File.separator + "classes/config.properties";
Properties localProperties = new Properties();
try {
FileInputStream localFileInputStream = new FileInputStream(str);
localProperties.load(localFileInputStream);
localFileInputStream.close();
} catch (FileNotFoundException localFileNotFoundException) {
logger.error("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
localFileNotFoundException.printStackTrace();
return null;
} catch (IOException localIOException) {
logger.error("装载文件--->失败!");
localIOException.printStackTrace();
}
return localProperties.getProperty(paramString);
}

public static String getRootPath() {
String result = null;
try {
result = CMConstant.class.getResource("CMConstant.class").toURI()
.getPath().toString();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
int index = result.indexOf("WEB-INF");
if (index == -1) {
index = result.indexOf("bin");
}
result = result.substring(1, index);
if (result.endsWith("/"))
result = result.substring(0, result.length() - 1);// 不包含最后的"/"
return result;
}
<span style="white-space:pre"> </span>/**
* 查找config/jdbc.properties里值
* @Description: @param key
* @Description: @return
* @Last Modified: , Date Modified:
*/
public static String getJDBCValue(String key) {
String filePath = getRootPath() + File.separator + "WEB-INF\\classes"
+ File.separator + "config.properties";
Properties propertie = new Properties();
try {
FileInputStream inputFile = new FileInputStream(filePath);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return null;
} catch (IOException ex) {
ex.printStackTrace();
}
return propertie.getProperty(key);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java web jdbc