package com.ctfo.core.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import com.ctfo.core.constant.CommonCode;
public class PropertyUtil extends PropertyPlaceholderConfigurer{
private final static Logger logger = Logger.getLogger(PropertyUtil.class);
private static Map<String, String> mapProperties;
//该方法只被加载一次,然后会将properties文件中的值以key-value形式存入到mapProperties中。
private static void processProperties(Properties props) throws BeansException {
if (mapProperties == null) {
mapProperties = new HashMap<String, String>();
}
Iterator<Entry<Object, Object>> iterator = props.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) iterator.next();
String strKey = (String) entry.getKey();
String strValue = (String)entry.getValue();
try {
strValue=new String(strValue.getBytes("ISO-8859-1"), "GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapProperties.put(strKey, strValue);
}
}
public static String getContextProperty(String name) {
if (mapProperties == null || mapProperties.size() == 0) {
//其中(CommonCode.strPropFolder)是properties配置文件所在上级文件夹名,即“config”,FileAndFolderUtil.getClassPath()获取项目根路径,
//strConfPath是文件夹路径
String strConfPath = FileAndFolderUtil.getClassPath() + CommonCode.strPropFolder;
// System.out.println("---------->path=" + FileAndFolderUtil.getClassPath() );
//其中(CommonCode.strPropSuffix)是properties文件后缀,即“properties”,获取文件名字
List<String> lsFilePath = FileAndFolderUtil.getFileName(strConfPath, CommonCode.strPropSuffix, false);
if (lsFilePath == null || lsFilePath.size() == 0) {
return "";
}
for (String strPath : lsFilePath) {
ClassPathResource resource = new ClassPathResource(CommonCode.strPropFolder + "/" + strPath);
Properties props = null;
try {
props = PropertiesLoaderUtils.loadProperties(resource);//读取properties文件中的信息
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
logger.info("getContextProperty exception:" + e.toString());
}
processProperties(props);//将其放入mapProperties中。
}
}
return (String) mapProperties.get(name);然后根据传入的key取出properties中的value值
}
//在使用的时候直接调用PropertyUtil.getContextProperty()方法即可。方法中需要传入properties文件中key,
//需要将CommonCode.strPropFolder、CommonCode.strPropSuffix替换为真实的值,然后可以直接使用。
public static void main(String[] args) {
System.out.println("---------->" + getContextProperty(CommonCode.strServTitle));
}
}
获取properties文件中的value值
猜你喜欢
转载自blog.csdn.net/wzm1994/article/details/73558608
今日推荐
周排行