简体   繁体   English

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

[英]Groovy code for reading a key:value from a text file

I have a config file config.txt with following key:values 我有一个配置文件config.txt具有以下键:值

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

I want to read the keys a nd b using groovy script but its giving following error message: 我想使用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

The code is as under: 代码如下:

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'

What am I missing? 我想念什么?

Pipeline DSL context runs on master node even that your write node('someAgentName') in your pipeline. 管道DSL上下文在master节点上运行,即使您在管道中的写入node('someAgentName')也是如此。 new File will work only on master. new File仅适用于主new File

But you can read data from file via sh() . 但是您可以通过sh()从文件读取数据。 Something like: 就像是:

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

I tested the following in the Groovy console and the assertions pass 我在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'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM