Java读取yml文件

之前在工作中遇到要将公司框架中的properties配置文件改成yaml, 在网上搜了一些资料

关于yaml文件的特性, 这里就不写了, 自己去查资料吧

直接上代码

maven依赖


	org.yaml
	snakeyaml
	1.25

测试yaml文件

spring:
  application:
    name: lele
    age: 23
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/test
    parson:
      name: 张三
      family:
        mother: 张三他娘
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.LinkedHashMap;

/**
 * @author jiale.he
 * @date 2019/10/10
 */
public class YmlDemo {
    public static void main(String[] args) {
        Yaml yaml = new Yaml();
        InputStream in = YmlDemo.class.getResourceAsStream("/app.yaml");
        LinkedHashMap<String, Object> sourceMap = (LinkedHashMap<String, Object>) yaml.load(in);
        String string = getString(sourceMap, "spring.datasource.url");
        System.out.println(string);
    }

    public static String getString(LinkedHashMap<String, Object> sourceMap, String key) {
        String[] keys = key.split("[.]");
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) sourceMap.clone();
        int length = keys.length;
        Object resultValue = null;
        for (int i = 0; i < length; i++) {
            Object value = map.get(keys[i]);
            if (i < length - 1) {
                map = ((LinkedHashMap<String, Object>) value);
            } else if (value == null) {
                throw new RuntimeException("key is not exists!");
            } else {
                resultValue = value;
            }
        }
        return resultValue.toString();
    }
}

输出结果
Java读取yml文件_第1张图片

你可能感兴趣的:(Java)