程序中修改yml

需要导入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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值