YAML
YAML 数据结构可以用类似大纲的缩排方式呈现,结构通过缩进来表示,连续的项目通过减号“-”来表示,map结构里面的key/value对用冒号“:”来分隔。
下面介绍两种 Java 读取 Yaml 内容的方式:
1.SnakeYaml
忽略注释的方式,读写会导致注释丢失
- 在pom.xml加入snakeyaml依赖:
org.yaml snakeyaml 1.29
- 具体java代码:
public class YamlUtils { private static final Logger logger = LoggerFactory.getLogger(YamlUtils.class); // yml2Map: Yaml to Map, 将yaml文件读为map public static Map yml2Map(String path) throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream(path); Yaml yaml = new Yaml(); Map ret = (Map) yaml.load(fileInputStream); return ret; } // map2Yml: Map to Yaml, 将map转换为yaml格式 public static void map2Yml(Map map, String path) throws IOException { File file = new File(path); FileWriter fileWriter = new FileWriter(file); DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options); yaml.dump(map, fileWriter); } }
2.eo-yaml:
- 支持注释读写的yaml包;
- 读取的时候,生成节点,在每一个节点上保存相应的注释;
- 写入的时候,根据节点,重新添加相应的注释;
com.amihaiemil.web eo-yaml 4.3.5
YamlMapping team = Yaml.createYamlInput( new File(path)).readYamlMapping();String architect = team.string("architect");YamlSequence devs = team.yamlSequence("developers");YamlSequence devops = team.yamlSequence("devops");
Map grades = new HashMap<>();grades.put("Math", 9);grades.put("CS", 10);YamlMapping student = Yaml.createYamlDump( new Student ("John", "Doe", 20, grades)).dumpMapping();
来源地址:https://blog.csdn.net/twi_twi/article/details/129949480