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

Java: How to merge two hocon config block into one?

我有两个配置

主要配置:main.conf

join {
  
}

需要合并到 main 中:test.conf

mergeMe {
  value = "SomeValue"
}

结果:

join {
  test {
    value = "SomeValue"
  }
}

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

我在科特林试过:

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()