我有一个看起来像这样的常规配置文件
section1 {
prop1 = val1
prop2 = val2
section2 {
prop3 = val3
{
}
// other style properties in this file
anotherprop = someval
// as well as some other statements
println "hello there"
例如,我想编写一个 groovy 脚本来更改 prop3 的值。在 groovy 中有没有好的方法来做到这一点?这有点困难,因为该文件包含多种样式的属性以及 println。
最佳答案
据我了解,您想修改配置文件。
由于文件中有 println
和其他语句,因此无法使用配置 Slurper 读取文件。
我想最简单的方法(但我希望这个解决方案会被否决)-:是使用 regsub:
def config = new File('config.groovy').getText()
def newValue = 18
def newConfig = config.replaceAll(/(?ms)(prop3[ \t]*=[ \t]*)([0-9]*)/,'$1'+newValue)
new File('config.groovy').write(newConfig)
在大多数情况下这应该是相当稳定的......
关于parsing - groovy更新配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12751230/