读取Yaml配置文件及Properties配置文件

读Yaml文件

所需依赖

// yml依赖
<dependency>
   <groupId>org.yaml</groupId>
   <artifactId>snakeyaml</artifactId>
   <version>1.26</version>
</dependency>

工具类

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;


public class YamlConf {
	//存储配置属性的Map集合
    private static Map<String, Object> conf = new HashMap<String, Object>();


    public static void init()throws IOException{
        //从classpath下获取配置文件路径
        URL url = YamlConf.class.getResource("/cluster.yml");
        Yaml yaml = new Yaml();
        //通过yaml对象将配置文件的输入流转换成map原始map对象
        Map map = yaml.loadAs(new FileInputStream(url.getPath()), Map.class);
        // 也可以这么读
        //Map map = yaml.loadAs(new FileInputStream(new File("src/main/resources/cluster.yml")), Map.class);
        
        //递归map对象将配置加载到conf对象中
        loadRecursion(map, "");
    }

    public static Object get(String key)throws Exception{
        if (conf.size() == 0){
            throw new Exception("未初始化,未找到配置数据项!");
        }
        return conf.get(key);
    }


    //递归解析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;
    }

	public static void main(String[] args) throws Exception{
        YamlConf.init();
        // 可以愉快的读取了
        YamlConf.get("xx.xx.xxx");
    }
}

读Properties文件

不需要单独引依赖

// 读取classpath下配置
import jodd.util.PropertiesUtil;

Properties props = PropertiesUtil.createFromFile("src/main/resources/jdbc.properties");
props.getProperty("hive_initialSize") // 取值

参考:
https://blog.csdn.net/hexiaodiao/article/details/86695664?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.nonecase

你可能感兴趣的:(技术)