【已解决】Java解析YAML代码实例(包含读取和写入yaml)
作者:互联网
文章目录
前言
创作开始时间:2021年8月3日14:45:39
如题,本文直接给出读取和写入yaml的代码实例。
环境
- jdk8
- ubuntu 16
- maven
代码实例
1)在pom.xml加入snakeyaml依赖:
<!-- read and write yaml file -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.29</version>
</dependency>
2)具体java代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
/**
* @author apr
* Aug 3, 2021
*/
public class YamlUtil {
public static Map<String, Object> readYaml(File file) {
Map<String, Object> data = null;
try {
InputStream inputStream = new FileInputStream(file);
// InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("customer.yaml");
Yaml yaml = new Yaml();
data = yaml.load(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return data;
}
public static void writeYaml(Map<String, Object> data, String filePath) {
Yaml yaml = new Yaml();
try {
PrintWriter writer = new PrintWriter(new File(filePath));
yaml.dump(data, writer);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
注意:
- snakeyaml是在jdk7下开发的。所以可能不支持jdk8的有些特性。比如:Add native support for parsing/serializing Java 8 date API https://bitbucket.org/asomov/snakeyaml/issues/419/add-native-support-for-parsing-serializing
- 除了snakeyaml,还有很多其他lib可以解析yaml:YamlBeans,eo-yaml,jackson
- 还有更复杂的功能,比如read yaml的时候输出为自定义的类,而不是map。目前暂时用不上。
小结
以上。
创作结束时间:2021年8月3日14:49:50
参考文献
主要参考:
- Reading and Writing YAML Files in Java with SnakeYAML https://stackabuse.com/reading-and-writing-yaml-files-in-java-with-snakeyaml
- Parsing YAML with SnakeYAML https://www.baeldung.com/java-snake-yaml
次要参考:
- How to read from YAML file in java? https://stackoverflow.com/questions/62989576/how-to-read-from-yaml-file-in-java
标签:java,YAML,snakeyaml,yaml,Java,io,new,import 来源: https://blog.csdn.net/weixin_39278265/article/details/119349891