Java读取yml配置文件到map中

时间:2025-04-05 09:09:50
public class App { //存储配置属性的Map集合 public static Map<String, Object> conf = new HashMap<String, Object>(); public static void main(String[] args) throws IOException { //从classpath下获取配置文件路径 URL url = App.class.getResource("/"); Yaml yaml = new Yaml(); //通过yaml对象将配置文件的输入流转换成map原始map对象 Map map = yaml.loadAs(new FileInputStream(url.getPath()), Map.class); //递归map对象将配置加载到conf对象中 loadRecursion(map, ""); System.out.println(conf.get("mysql.database1.table1")); } //递归解析map对象 public static void loadRecursion(Map<String, Object> map, String key){ map.forEach((k,v) -> { if(isParent(v)){ Map<String, Object> nextValue = (Map<String, Object>) v; loadRecursion(nextValue, (("".equals(key) ? "" : key + ".")+ k)); }else{ conf.put(key+"."+k,v); } }); } //判断是否还有子节点 public static boolean isParent(Object o){ if (!(o instanceof String || o instanceof Character || o instanceof Byte)) { try { Number n = (Number) o; } catch (Exception e) { return true; } } return false; } }