问题描述
我有两个配置
主配置: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()