在项目中,我们的配置文件并不是全部放在项目下的,有许多配置文件是放在本地磁盘中,因此我们需要经常从本地读取配置文件的内容。下面这个这个就是一个读取本地配置文件的工具类
该工具读取的是 路径/xiaoming/config/下的pro.properties配置文件,/xiaoming/config/是相对路径。表示和你的项目在本地磁盘的同一文件夹下
public class PropertiesUtil {
final static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
private static Map<String,Properties> propertiesMap=new ConcurrentHashMap<String,Properties>();
/**
* 获取配置文件
*/
private static String getConfPathByOS(){
String path="/xiaoming/config/";
return path;
}
/**
* 根据配置文件名加载配置
* @param valueName
* @return
*/
public static String getPropertiesString(String fileName, String valueName) {
String value=null;
if(propertiesMap.containsKey(fileName)){
Properties property=propertiesMap.get(fileName);
value=property.getProperty(valueName);
}else{
Properties property = new Properties();
InputStream in=null;
String path=getConfPathByOS()+fileName+".properties";
log.info("开始加载系统数据:"+path);
try{
in =new FileInputStream(path);
property.load(in);
propertiesMap.put(fileName, property);
value=property.getProperty(valueName);
}catch (FileNotFoundException ex){
log.info("读取属性文件 "+path+"--->失败!- 原因:文件路径错误或者文件不存在");
ex.printStackTrace();
} catch (IOException ex){
log.info("装载文件"+path+"--->失败!");
ex.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return value;
}
/**
* 根据默认配置文件加载配置
* @param valueName 属性名
* @return
*/
public static String getVal(String valueName) {
String fileName="pro";
return getPropertiesString( fileName, valueName);
}
}