需要导入Yaml依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.17</version>
</dependency>
@Override
public void updateServerConfig(String wardNos) {
DumperOptions OPTIONS = new DumperOptions();
//控制样式,下面的是按一般yml格式缩进的
OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
OPTIONS.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
OPTIONS.setPrettyFlow(false);
Yaml yaml = new Yaml(OPTIONS);
//InputStream stream = getClass().getResourceAsStream("/application.yml");
//打成jar包以后用该方法读取文件,不然可能报错
try (InputStream stream = new ClassPathResource("application.yml").getInputStream()) {
//获取yml的值并将值转换为Map
Map m1 = (Map) yaml.load(stream);
Map m2 = (Map) m1.get("server");
//替换yml的值
m2.put("wardNos", wardNos);
//将数据重新写回文件,但是这种方法文件的注释就没了
URL fileURL = this.getClass().getResource("application.yml");
yaml.dump(m1, new FileWriter(fileURL.getFile()));
} catch (IOException e) {
e.printStackTrace();
}
}
程序中修改yml
最新推荐文章于 2023-12-06 18:35:27 发布