簡體   English   中英

用於從文本文件讀取key:value的Groovy代碼

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

我有一個配置文件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'

我想念什么?

管道DSL上下文在master節點上運行,即使您在管道中的寫入node('someAgentName')也是如此。 new File僅適用於主new File

但是您可以通過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()

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