properties,xml,yaml配置文件解析

读取几种配置文件

        java中,常见几种配置文件有:.properties,.xml,.yml,spring项目中对这些类型的配置文件通常有现成可用的封装,下面用手动解析的方式来操作这些类型配置文件;

首先idea创建项目:

  1. properties
  2. 根目录下创建配置文件:application.properties,和测试类Test.java

    application.properties配置文件中,设置几个基础配置项:

    Test.java中编写readFromProperties()方法解析文件:

    public static Map readFromProperties() {
        Map result = new HashMap<>();
        Properties properties = new Properties();
        try (FileInputStream inputStream = new FileInputStream("read-config/application.properties")) {
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!properties.keySet().isEmpty()) {
            for (Object key : properties.keySet()) {
                result.put(key.toString(), properties.getProperty(key.toString()));
            }
        }
        return result;
    }
    .properties配置文件可以通过jdk中的java.util.Properties类进行读取和解析,注意application.properties文件路径。
    测试:


  3. xml
  4. application.properties同级目录下创建xml配置文件config.xml,并写入简单配置信息:

    Test.java中编写readFromXml()方法解析文件:

    public static Map readFromXml() {
        Map result = new HashMap<>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document document = documentBuilder.parse(new File("read-config/config.xml"));
            result = node(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    private static Map node(Node node) {
        Map result = new HashMap<>();
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            //元素节点-递归
            if (item.getNodeType() == Node.ELEMENT_NODE) {
                result.putAll(node(item));
            }
            //文本节点-添加map
            else if (item.getNodeType() == Node.TEXT_NODE
                    && null != item.getNodeValue()
                    && !"".equals(item.getNodeValue().trim())
                    && !"\n".equals(item.getNodeValue().trim())) {
                result.put(item.getParentNode().getNodeName(), item.getNodeValue());
            }
        }
        return result;
    }

    代码分析:
    xml解析主要用到javax.xml.parsers包下的两个类:DocumentBuilderFactoryDocumentBuilder,通过documentBuilder.parse(new File("read-config/config.xml"))方法解析xml文件为Document对象。接着用方法node(Node node)递归Document对象各节点到Map对象。Document本身也是Node对象

    打印结果:


  5. yaml
  6. application.properties同级目录下创建yaml配置文件config.yml,并写入简单配置信息:

    由于jdk没有提供yaml解析工具,需要手动导入解析库,这里用的库是:snakeyaml-1.29.jar

    通过snakeyaml库,可以解析yaml配置文件为map或者对象。

    该工具库下载地址参考:https://mvnrepository.com/artifact/org.yaml/snakeyaml

    解析到Map

    public static void readFromYml2Map() {
        try (FileReader reader = new FileReader("read-config/config.yml")) {
            Yaml yaml = new Yaml();
            Object load = yaml.load(reader);
            if (load instanceof Map) {
                Map map = (Map) load;
                System.out.println("======");
                for (Object o : map.keySet()) {
                    System.out.println("-|key:" + o + "\tvalue:" + map.get(o));
                    if (map.get(o) instanceof Map) {
                        Map map1 = (Map) map.get(o);
                        for (Object o1 : map1.keySet()) {
                            System.out.println("\t--|key:" + o1 + "\tvalue:" + map1.get(o1));
                        }
                    }
                    System.out.println("======");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    代码说明:解析到Map核心方法是通过yaml.load(reader),该方法将会返回一个Map对象。输出结果如下:


    解析为对象

    public static void readFromYml2Entity() {
        try (FileReader reader = new FileReader("read-config/config.yml")) {
            Yaml yaml = new Yaml();
            ConfigEntity entity = yaml.loadAs(reader, ConfigEntity.class);
            System.out.println("======");
            System.out.println(entity);
            System.out.println("======");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    代码说明:解析到对象核心方法是通过yaml.loadAs(reader, ConfigEntity.class)。输出结果如下:


  7. 总结
  8.         以上就是properties,xml,yaml三种配置文件解析的方法,这三种配置文件个人建议是简单的配置用properties,层次结构复杂的配置建议用yaml,xml虽然结构清晰但是配置没yaml简洁可根据情况取舍。

尊重原创,转载请标明出处,谢谢

posted @ 2021-07-14 15:38  zhoux_top  阅读(436)  评论(0编辑  收藏  举报