创作开始时间:2021年8月3日14:45:39
如题,本文直接给出读取和写入yaml的代码实例。
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(); } } }
注意:
以上。
创作结束时间:2021年8月3日14:49:50
主要参考:
次要参考: