博客
关于我
Java解析yaml
阅读量:628 次
发布时间:2019-03-14

本文共 2547 字,大约阅读时间需要 8 分钟。

读取YAML文件并转换为Map的处理流程如下:

代码解释

import java.io.File;import java.io.FileInputStream;import java.util.Iterator;import java.util.Map;import org.yaml.snakeyaml.Yaml;public class YAMLTest {    public static void main(String[] args) throws Exception {        // 读取YAML文件        Yaml yaml = new Yaml();        File file = new File("D:/test.yaml");        Object load = yaml.load(new FileInputStream(file));        // 另一种常见方法:直接读取资源文件        // InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yml");        // Object load = yaml.load(io);        System.out.println("加载结果:\n" + yaml.dump(load));        System.out.println(" ############################################################################# ");        // 将YAML文件转换为Map
Map
map = (Map
) yaml.load(new FileInputStream(file)); System.out.println("转换后的Map:\n" + yaml.dump(map)); System.out.println(" ############################################################################# "); // 遍历Map中的键值对 Iterator
> entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry
entry = entryIterator.next(); String key = entry.getKey(); Object value = entry.getValue(); if (key.equals("ip") || key.equals("port")) { String valueStr = (String) value; System.out.println("键值对:" + key + ":" + valueStr); } else { System.out.println("这是一个嵌套的Map结构,处理方式如下:"); if (key.equals("server")) { Map
subMap = (Map
) value; Iterator
> subEntryIterator = subMap.entrySet().iterator(); while (subEntryIterator.hasNext()) { Map.Entry
subEntry = subEntryIterator.next(); String subKey = subEntry.getKey(); Object subValue = subEntry.getValue(); if (subKey.equals("port2")) { System.out.println("子键:" + subKey + ":" + subValue); } } } else { System.out.println("普通键值对:" + key + ":" + value); } } System.out.println(" ############################################################################# "); } }}

运行结果展示

ip: 192.168.102.31port: 7788spring:  application: {name: cruncherserver: {port2: 9000}}monitor_nic:  nic: {name: ethA, slot: 0, cpu: 0}#############################################################################这一行用于分隔代码输出和解释段键值对:ip: 192.168.102.31键值对:port: 7788这是一个嵌套的Map结构,处理方式如下:普通键值对:spring: {application={name=cruncher}}键值对:server: {port=9000}键值对:monitor_nic: {nic={name=ethA, slot=0, cpu=0}}

Maven依赖说明

org.yaml
snakeyaml
1.26

转载地址:http://ednoz.baihongyu.com/

你可能感兴趣的文章
Nim教程【十二】
查看>>
Nim游戏
查看>>
NIO ByteBuffer实现原理
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NIO三大组件基础知识
查看>>
NIO与零拷贝和AIO
查看>>
NIO同步网络编程
查看>>
NIO基于UDP协议的网络编程
查看>>
NIO笔记---上
查看>>
NIO蔚来 面试——IP地址你了解多少?
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NISP国家信息安全水平考试,收藏这一篇就够了
查看>>
NIS服务器的配置过程
查看>>
Nitrux 3.8 发布!性能全面提升,带来非凡体验
查看>>
NiuShop开源商城系统 SQL注入漏洞复现
查看>>
NI笔试——大数加法
查看>>
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>