这里提供解析的辅助方法
package com.cms.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class MiscUtil {
private static Map<String, String> configProperty = null;
private static String configPropertyPath="classpath:jdbc.properties";
/**
* 从application.properties 文件中有key获取values
* @param key
* @return
*/
public static String getConfigByKey(String key) {
if(isEmptyString(key)){ return null; }
try{
if(configProperty==null){
configProperty= MiscUtil.convertPropertiesFileToMap(configPropertyPath);
}
} catch(Exception e){
//TODO add log info
e.printStackTrace();
}
return configProperty.get(key).trim();
}
public static boolean isEmptyString(String value){
return value==null?true:(value.trim().length()<1?true:false);
}
public static Map<String, String> convertPropertiesFileToMap(String path) throws Exception{
InputStream input = null;
Map<String,String> propertiesMap = null;
try{
if(path.toLowerCase().startsWith("classpath:")){
String fileName = path.substring("classpath:".length());
input = MiscUtil.class.getClassLoader().getResourceAsStream(fileName);
if(input==null){
path=MiscUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
path=path.substring(0, path.lastIndexOf(File.separatorChar)+1)+fileName;
}
}
if(input==null){
input = new FileInputStream(path);
}
Properties properties = new Properties();
properties.load(new InputStreamReader(input, "UTF-8"));
propertiesMap = new HashMap<String,String>();
for(String name : properties.stringPropertyNames()){
propertiesMap.put(name, properties.getProperty(name));
}
}finally{
if(input!=null){
input.close();
}
}
return propertiesMap;
}
}
代码中 properties.load(new InputStreamReader(input, "UTF-8")); 这里是设置内容格式防止中文乱码的情况
下面给新手一点技巧 如果想要直接看到中文的话要把该文件的格式设置为utf-8 则可以看到中文
下图是 UNicode 码 该文件的格式为 iso-8859-1