package net.geedge.confagent.util; import cn.hutool.core.util.StrUtil; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.yaml.snakeyaml.Yaml; import java.io.BufferedReader; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class YamlUtil { public static void writeAsMap(Map map,String path){ Map writeObj = map; if(writeObj == null) writeObj = new HashMap<>(); Yaml yaml = new Yaml(); Tool.FileUtil.writeUtf8String(yaml.dumpAsMap(writeObj), path); } /** * @Description 将yaml文件中的内容读取到map中 * @Author rui * @Date 2021/3/24 */ public static Map readAsMap(String path){ File file = Tool.FileUtil.file(path); Yaml yaml = new Yaml(); BufferedReader reader = Tool.FileUtil.getReader(file, Tool.CharsetUtil.UTF_8); Map map = yaml.loadAs(reader, Map.class); Tool.IoUtil.close(reader); return map; } /** * @Description 读取yaml文件中的属性,支持spring.profiles.active 连点形式 * @Author rui * @Date 2021/3/23 */ public String readProperty(String file,String key){ Resource resource = getResource(file); Properties properties = yamlToProperties(resource); return properties.getProperty(key); } /** * @Description 读取yaml文件中的属性,可以指定默认值 * @Author rui * @Date 2021/3/23 */ public String readProperty(String file,String key,String defValue){ Resource resource = getResource(file); Properties properties = yamlToProperties(resource); return properties.getProperty(key,defValue); } /** * @Description 获取application相关配置文件 * @Author rui * @Date 2021/3/23 */ public static Resource getApplication(String mode, String profile){ return getResource("application"+ (StrUtil.isEmpty(profile)?"":"-"+profile )+".yml"); } /** * @Description 获取配置文件 * @Author rui * @Date 2021/3/23 */ public static Resource getResource(String file){ return new FileSystemResource(file); } /** * @Description 读取yaml文件并转为properties对象 * @Author rui * @Date 2021/3/23 */ public static Properties yamlToProperties(String file){ Resource resource = getResource(file); return yamlToProperties(resource); } public static Properties yamlToProperties(String ... filepath){ return yamlToProperties(getFileAbsolutePath(filepath)); } /** * @Description 读取yaml文件并转为properties对象 * @Author rui * @Date 2021/3/23 */ public static Properties yamlToProperties(Resource resource){ YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); // 2:将加载的配置文件交给 YamlPropertiesFactoryBean yamlPropertiesFactoryBean.setResources(resource); // 3:将yml转换成 key:val return yamlPropertiesFactoryBean.getObject(); } public static String getFileAbsolutePath(String ... path){ return Tool.FileUtil.file(path).getAbsolutePath(); } }