2016-02-26 34 views
0

我很感興趣,如果有一種簡單的方法來將文件中的特定行存儲到Groovy中的數組(我需要它在Jenkins中的GroovyAxis)。該文件應該是這樣的:如何從Groovy中的數組中的文件中存儲特定的行?

var1="value1 value2 etc" 

var2="a b etc" 

var3="test1 test2 test3 etc" 

我需要測試1測試2 TEST3等從VAR3存儲在陣列中。現在我用這個:

def words = [] 
new File('/home/workstation/jenkins/params').eachLine { line -> 
    words << line 
} 

但它存儲的每一行,我有到一個數組,所以我必須大力解決該配置文件來完成這項工作。

非常感謝你

+0

'如果(line.startsWith(「VAR3 ='))'?你有什麼嘗試?具體問題是什麼? –

+0

你好,謝謝你的回答。我對Groovy沒有任何認識(但是這是我在Jenkins必須做的事情的唯一方法)。上面的代碼我發現了另一個問題發佈在這裏。我試圖尋找修改方法來做我想做的事情,但沒有成功。具體的問題是,我還沒有找到一種方法來存儲test1 test2 test3等沒有var3 =或「,只是之間的值」。 – Georgian

+0

Groovy在JVM上運行,並使用Java字符串。閱讀String的javadoc。它有像startsWith,substring,split等方法。 –

回答

0

你是非常接近!

def words = [:] 
new File('/home/workstation/jenkins/params').eachLine { line -> 
    (var, value) = line.split('=') 
    words << [(var): value.split(' ')] 
} 

結果是數組映射。關鍵是變量名稱,值是一個數組。

更新

哦,這是一個屬性文件...

Properties properties = new Properties() 
File propertiesFile = new. File('/home/workstation/jenkins/params') 
propertiesFile.withInputStream { properties.load(it) } 
def result = properties.var3.split(' ').collect { item.minus('"') } 
return result 
+0

我忘了過濾掉雙引號。在我的頭頂,我只是不記得如何去做。 –

+0

謝謝,有一點改變,它工作正常。我做了這樣一個醜陋的方式(我不知道Groovy):'def result = [] Properties properties = new Properties() File propertiesFile = new File('/ home/workstation/jenkins/params') propertiesFile.withInputStream { properties.load(它) } 緩衝液= properties.var3 緩衝器2 = buffer.split(」「).toList() 用於(在緩衝器2項){ 結果=結果+項.minus(''') }' 返回結果 – Georgian

0

ConfigSlurper可能是有用的加載性能/配置:

def config = new ConfigSlurper(new File("my.conf").toURL()) 
assert config.var2 == "a b etc" 
相關問題