java解析yaml_YAML配置文件解析器:SnakeYAML
本篇blog主要是讨论:
如何使用SnakeYAML来读取YAML(YML为其简写)配置文件;
读取后,装载成Map,而Map如何存储的配置文件的数据。
SnakeYAML的简介
SnakeYAML是针对java语言的YAML解析器。如果想更多的了解SnakeYAML和YMAL,请看blog:
如何读取YAML配置文件
请看代码:
FileInputStream fileInputStream = null;
try {
Yaml yaml = new Yaml();//实例化解析器
File file = new File("inscriber-s\\src\\main\\resources\\application.yml");//配置文件地址
fileInputStream = new FileInputStream(file);
Map map = yaml.loadAs(fileInputStream, Map.class);//装载的对象,这里使用Map, 当然也可使用自己写的对象
//printMap(map, 0);
}catch(FileNotFoundException e) {
log.error("文件地址错误");
e.printStackTrace();
}finally {
try {
if(fileInputStream!=null) fileInputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
Map是如何存储的配置文件数据
以下面的.yml配置文件为例:
# mybatis
mybatis:
type-aliases-package: info.ideatower.component.inscriber.entity
mapper-locations: classpath:mapping/*.xml
config-locations: classpath:mybatis-config.xml
# 应用组件通信等配置
component:
misso:
log:
addr: http://localhost:8009
error:
enable: on
Related:
Projects:
- Rx
- Kwalify
- yaml_vim
- yatools.net
- JSON
- Pygments
使用SnakeYAML进行装载,实例化成Map对象(确切的说,应该是Map的子类,LinkedHashMap)。值得注意的是,要装载如此复杂的配置文件的,必须使用Map的嵌套,即:Map嵌套Map。具体请看下图:

其中,椭圆圈为key, 矩形圈的为value, 嵌套结构显而易先。如下图:

一般的,key的类类型总是java.lang.Stirng, 而value的类类型是不尽相同的。请看下图:

小小的拓展
一段打印Map的数据的函数,如果读懂的话,会更加理解本篇blog的内容:
private void printMap(Map map, int count){
Set set = map.keySet();
for(Object key: set){
Object value = map.get(key);
for(int i=0; i
System.out.print(" ");
}
if(value instanceof Map) {
System.out.println(key+":");
printMap((Map)value, count+1);//嵌套
}else if(value instanceof List){
System.out.println(key+":");
for(Object obj: (List)value){
for(int i=0; i
System.out.print(" ");
}
System.out.println(" - "+obj.toString());
}
}else{
System.out.println(key + ": " + value);
}
}
}
end