YAML
The YAML data structure can be presented in an outline-like indentation manner. The structure is represented by indentation, and consecutive items are represented by a minus sign "-", and the key/value pairs in the map structure are separated by a colon ":".
Here are two ways for Java to read Yaml content:
1.SnakeYaml
The way to ignore comments, reading and writing will cause comments to be lost
- Add snakeyaml dependency to pom.xml:
<!-- read and write yaml file -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.29</version>
</dependency>
- Specific java code:
public class YamlUtils {
private static final Logger logger = LoggerFactory.getLogger(YamlUtils.class);
// yml2Map: Yaml to Map, 将yaml文件读为map
public static Map<String, Object> yml2Map(String path) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(path);
Yaml yaml = new Yaml();
Map<String, Object> ret = (Map<String, Object>) yaml.load(fileInputStream);
return ret;
}
// map2Yml: Map to Yaml, 将map转换为yaml格式
public static void map2Yml(Map<String, Object> 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:
- A yaml package that supports reading and writing comments;
- When reading, generate nodes and save corresponding comments on each node;
- When writing, re-add corresponding comments according to the node;
<dependency>
<groupId>com.amihaiemil.web</groupId>
<artifactId>eo-yaml</artifactId>
<version>4.3.5</version>
</dependency>
YamlMapping team = Yaml.createYamlInput(
new File(path)
).readYamlMapping();
String architect = team.string("architect");
YamlSequence devs = team.yamlSequence("developers");
YamlSequence devops = team.yamlSequence("devops");
Map<String, Integer> grades = new HashMap<>();
grades.put("Math", 9);
grades.put("CS", 10);
YamlMapping student = Yaml.createYamlDump(
new Student ("John", "Doe", 20, grades)
).dumpMapping();