代码之家  ›  专栏  ›  技术社区  ›  Yash

用于读取键的Groovy代码:文本文件中的值

  •  0
  • Yash  · 技术社区  · 7 年前

    我有一个配置文件 config.txt 使用以下键:值

    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'
    

    我错过了什么?

    2 回复  |  直到 7 年前
        1
  •  3
  •   FCh    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()
    
        2
  •  0
  •   Dónal    7 年前

    我在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'
    }