2017-07-10 24 views
0

我想從我的實際腳本groovy文件中分離變量數據。使用單獨的數據文件來讀取groovy變量

def test = [a,b,c] 
def test2 = ['foo': [a,x,y], 'bar': [q,w,e]] 


def function(String var){} 
def function2 { 
test.each 
{ 
    item -> 
print test 


} 
} 

因爲我在變量中的值不斷變化,但不是腳本。如何讓我的groovy在運行時讀取一個變量文件並加載它?

我希望它看起來像這樣也許。

variables.properties 
def test = [a,b,c] 
def test2 = ['foo': [a,x,y], 'bar': [q,w,e]] 

main.groovy

load (variable.properties) 

def function(String var){} 
def function2 { 
test.each 
{ 
    item -> 
print test 


} 
} 
+0

你會怎樣想的文件是什麼樣子? – daggett

+0

@daggett我更新了我的問題來回答這個問題 – ShakyaS

+0

您是否需要將變量定義明確地指定爲Groovy,還是隻使用任何常規數據格式(例如JSON屬性)? –

回答

0

在Groovy中,它是能夠評價數據作爲Groovy代碼。這是一個強大的技術。這對於你的目標來說可能有點多,但是會起作用。

考慮這個config.data文件(它是一個Groovy文件,但可以任意取名):

test = ['a','b','c'] 
test2 = ['foo': ['a','x','y'], 'bar': ['q','w','e']] 

App.groovy文件。它在GroovyShell中設置了一個Binding變量。在shell中對Config進行求值,我們可以在主應用程序中引用這些變量。

def varMap = [:] 
varMap["test"] = [] 
varMap["test2"] = [:] 

def binding = new Binding(varMap) 
def shell = new GroovyShell(binding) 

def function2 = { test, test2 -> 
    test.each { println "test item: ${it}" } 
    test2.each { println "test2 item: ${it}" } 
} 

// ------ main 

// load Config and evaluate it 
def configText = new File(args[0]).getText() 
shell.evaluate(configText) 

def test = varMap["test"] 
def test2 = varMap["test2"] 

function2(test, test2) 

用法的例子:

$ groovy App.groovy config.data 
test item: a 
test item: b 
test item: c 
test2 item: foo=[a, x, y] 
test2 item: bar=[q, w, e] 
+0

'java.io.FileNotFoundException:config.data(沒有這樣的文件或目錄)' 我得到這個錯誤 – ShakyaS

+0

'config.data'文件必須與'App.groovy'文件在同一個目錄中,並且如上所述通過命令行傳遞。 –

+0

謝謝。它的工作 – ShakyaS

相關問題