博客
关于我
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/

你可能感兴趣的文章
php实现短信验证功能
查看>>
RabbitMQ连接报错(1)—— None of the specified endpoints were reachable
查看>>
php实现逆转数组
查看>>
PHP实现通过geoip获取IP地理信息
查看>>
PHP实现页面静态化、纯静态化及伪静态化
查看>>
php容许ajax跨域,PHP设置允许ajax跨域请求的两种常见方法
查看>>
RabbitMQ进程结构分析与性能调优
查看>>
PHP对接百度地图
查看>>
PHP对表单提交特殊字符的过滤和处理
查看>>
php对象引用和析构函数的关系
查看>>
RabbitMQ HTTP 认证后端项目常见问题解决方案
查看>>
PHP将图片转换成base64格式(优缺点)
查看>>
php将多个值的数组去除重复元素
查看>>
php局域网上传文件_PHP如何通过CURL上传文件
查看>>
PHP工具插件大全
查看>>
php布尔值的++
查看>>
PHP常量、变量作用域详解(一)
查看>>
PHP应用目录结构设计
查看>>
PHP应用程序连接MSQL数据库Demo(附crud程序)
查看>>
PHP应用程序连接Oracle数据库Demo(附Oracle客户端安装文件)
查看>>