importorg.apache.commons.lang3.StringUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.util.ResourceUtils;importorg.yaml.snakeyaml.Yaml;import java.io.*;importjava.util.HashMap;importjava.util.Map;importjava.util.Set;/***@authorhunmeng
* @create 2020-01-10 20:34*/
public classYmlUtils {private static final Logger LOGGER = LoggerFactory.getLogger(YmlUtils.class);private static String bootstrap_file = "classpath:application-test.yml";private static Map result = new HashMap<>();/*** 根据文件名获取yml的文件内容
*@paramfilePath
*@paramkeys 第一个参数对应第一个key,第二个参数对应第二个key 比如spring.name下的所有 就是两个参数、
* getYmlByFileName(bootstrap_file,"spring", "name");
*@return
*/
public static MapgetYmlByFileName(String filePath, String... keys) {
result= new HashMap<>();if(filePath == null) filePath =bootstrap_file;
InputStream in= null;try{
File file=ResourceUtils.getFile(filePath);
in= new BufferedInputStream(newFileInputStream(file));
Yaml props= newYaml();
Object obj= props.loadAs(in,Map.class);
Map param = (Map) obj;for(Map.Entryentry:param.entrySet()){
String key=entry.getKey();
Object val=entry.getValue();if (keys.length != 0 && !keys[0].equals(key)){continue;
}if(val instanceofMap){
forEachYaml(key,(Map) val, 1, keys);
}else{
result.put(key, val.toString());
}
}returnresult;
}catch(FileNotFoundException e) {
LOGGER.error(e.getMessage(),e);
}finally{if (in != null){try{
in.close();
}catch(IOException e) {
LOGGER.error(e.getMessage(),e);
}
}
}return null;
}/*** 根据key获取值
*@paramkey
*@return
*/
public static String getValue(String key) throwsFileNotFoundException {
Map map = getYmlByFileName(null);if(map==null)return null;returnmap.get(key);
}/*** 遍历yml文件,获取map集合
*@paramkey_str
*@paramobj
*@parami
*@paramkeys
*@return
*/
public static Map forEachYaml(String key_str,Map obj, inti, String... keys){for(Map.Entryentry:obj.entrySet()){
String key=entry.getKey();
Object val=entry.getValue();if (keys.length > i && !keys[i].equals(key)){continue;
}
String str_new= "";if(StringUtils.isNotEmpty(key_str)){
str_new= key_str+ "."+key;
}else{
str_new=key;
}if(val instanceofMap){
forEachYaml(str_new,(Map) val, ++i, keys);
i--;
}else{
result.put(str_new,val.toString());
}
}returnresult;
}/*** 获取bootstrap.yml的name
*@return
*/
public static String getApplicationName() throwsFileNotFoundException {return getYmlByFileName(bootstrap_file).get("server.port");
}/*** 获取bootstrap.yml的name
*@return
*/
public static String getApplicationName1() throwsFileNotFoundException {
String name= getYmlByFileName(bootstrap_file).get("spring.application.name");return name + "center";
}public static void main(String[] args) throwsFileNotFoundException {
Map ymlByFileName = getYmlByFileName(bootstrap_file,"spring");
Set> entries =ymlByFileName.entrySet();for (Map.Entryentry : entries) {
System.out.println(entry.getKey()+"==="+entry.getValue());
}
System.out.println(getApplicationName());
}
}