本文共 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文件转换为MapMap 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}}
org.yaml snakeyaml 1.26
转载地址:http://ednoz.baihongyu.com/