微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java:如何将两个 hocon 配置块合并为一个?

如何解决Java:如何将两个 hocon 配置块合并为一个?

我有两个配置

主配置:main.conf

join {
  
}

需要合并到 main: test.conf

mergeMe {
  value = "SomeValue"
}

结果:

join {
  test {
    value = "SomeValue"
  }
}

合并块的名称与合并文件名称相同

我在 kotlin 中尝试过:

val main = ConfigFactory.parseFile(File("main.conf")).getConfig("join")
val test = ConfigFactory.parseFile(File("test.conf")).getConfig("mergeMe")
val joined = main.withOnlyPath("test").resolveWith(test,ConfigResolveOptions.defaults()).root().render(ConfigRenderOptions.defaults()
  .setComments(true)
  .setFormatted(true)
  .setJson(false).setoriginComments(true))
val writer = FileWriter(File("main.conf"))
writer.write(joined)
writer.flush()
writer.close()

更新:atPath 将使用新路径包装配置,应该使用 getConfig("mergeMe") 但仍然不起作用...

它不起作用...

怎么做?

解决方法

先获取合并块,并用源块名称包裹

然后我们可以通过使用 Config#withFallback 来合并这两个配置

// get the config block which will contain the merge block
val main = ConfigFactory.parseFile(File("main.conf"))
// get merge block and wrap with contain block name
val test = ConfigFactory.parseFile(File("test.conf")).getConfig("mergeMe").atPath("join.test")
// merge two block into one and convert to string
val joined = main.withFallback(test).root().render(ConfigRenderOptions.defaults()
  .setFormatted(true)
  .setJson(false)
  .setComments(true)
  .setOriginComments(false))
val writer = FileWriter(File("main.conf"))
writer.write(joined)
writer.flush()
writer.close()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。