Groovy 从文本文件中读取 key:value 的代码

Groovy code for reading a key:value from a text file

我有一个配置文件 config.txt 包含以下内容 key:values

a=1,2,3
b=5,6,7

我想使用 groovy 脚本读取键 a 和 b 但它给出了以下错误消息:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods withInputStream java.io.File groovy.lang.Closure

代码如下:

Properties properties = new Properties()
File propertiesFile = new File('config.txt')
propertiesFile.withInputStream {
    properties.load(it)
}

def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'

我错过了什么?

我在 Groovy 控制台中测试了以下内容并且断言通过了

new File('config.txt').withReader {
   def props = new Properties()
   props.load(it)

   assert props.getProperty('a') == '1,2,3'
   assert props.getProperty('b') == '5,6,7'
}

管道 DSL 上下文在 master 节点上运行,即使您在管道中写入 node('someAgentName')new File 仅适用于 master。

但是您可以通过sh()从文件中读取数据。类似于:

def a = sh(returnStdout: true, script: "cat config.txt | grep a | cut -f2 -d'='").trim()
def b = sh(returnStdout: true, script: "cat config.txt | grep b | cut -f2 -d'='").trim()