2013-11-21 36 views
1

我是Groovy的新手,無法解決此問題。我感謝任何幫助。groovy讀取文件,解決文件內容中的變量

我想從Groovy中讀取文件。在閱讀內容時,對於每行我想用不同的字符串值替換字符串'$ {random_id}'和'$ {entryAuthor}'。

protected def doPost(String url, URL bodyFile, Map headers = new HashMap()) { 
    StringBuffer sb = new StringBuffer() 
    def randomId = getRandomId() 
    bodyFile.eachLine { line -> 
     sb.append(line.replace("\u0024\u007Brandom_id\u007D", randomId) 
        .replace("\u0024\u007BentryAuthor\u007D", entryAuthor)) 
     sb.append("\n") 
    } 
    return doPost(url, sb.toString()) 
} 

但我得到了以下錯誤:

groovy.lang.MissingPropertyException: 
No such property: random_id for class: tests.SimplePostTest 
Possible solutions: randomId 
    at foo.test.framework.FooTest.doPost_closure1(FooTest.groovy:85) 
    at groovy.lang.Closure.call(Closure.java:411) 
    at groovy.lang.Closure.call(Closure.java:427) 
    at foo.test.framework.FooTest.doPost(FooTest.groovy:83) 
    at foo.test.framework.FooTest.doPost(FooTest.groovy:80) 
    at tests.SimplePostTest.Post & check Entry ID(SimplePostTest.groovy:42) 

它爲什麼會抱怨的屬性,當我沒有做任何事情?我也嘗試過「\ $ \ {random_id \}」,它在Java String.replace()中工作,但不在Groovy中。

+0

錯誤看起來正確。我沒有在您發佈的代碼中看到名爲'random_id'的屬性,我看到一個名爲'randomId'的屬性。該屬性'random_id'確實缺失:) – ubiquibacon

+0

問題是我沒有試圖檢索名爲random_id的屬性的值。 –

回答

0

這裏的問題是,Groovy字符串將通過替換'x'的值來評估「$ {x}」,並且在這種情況下我們不希望這種行爲。訣竅是使用單引號表示普通的舊Java字符串。

使用這樣的數據文件:

${random_id} 1 ${entryAuthor} 
${random_id} 2 ${entryAuthor} 
${random_id} 3 ${entryAuthor} 

考慮以下代碼,它類似於原:

// spoof HTTP POST body 
def bodyFile = new File("body.txt").getText() 

StringBuffer sb = new StringBuffer() 
def randomId = "257" // TODO: use getRandomId() 
def entryAuthor = "Bruce Eckel" 

// use ' here because we don't want Groovy Strings, which would try to 
// evaluate e.g. ${random_id} 
String randomIdToken = '${random_id}' 
String entryAuthorToken = '${entryAuthor}' 

bodyFile.eachLine { def line -> 
    sb.append(line.replace(randomIdToken, randomId) 
        .replace(entryAuthorToken, entryAuthor)) 
    sb.append("\n") 
} 

println sb.toString() 

輸出是:

257 1 Bruce Eckel 
257 2 Bruce Eckel 
257 3 Bruce Eckel 
+0

真棒@MichaelEaster。這樣可行!感謝您的建議。 –

0

你正在做的這是困難的方式。只需使用Groovy的SimpleTemplateEngine評估您的文件內容即可。

import groovy.text.SimpleTemplateEngine 

def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}' 

def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"] 

def engine = new SimpleTemplateEngine() 
template = engine.createTemplate(text).make(binding) 

def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev' 

assert result == template.toString()