groovy读取文件,解析文件内容中的变量

时间:2013-11-21 23:14:26

标签: 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中没有。

3 个答案:

答案 0 :(得分:4)

你正在以艰难的方式去做。只需使用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()

答案 1 :(得分:3)

你最好使用groovy.text.SimpleTemplateEngine类;查看此详细信息http://groovy.codehaus.org/Groovy+Templates

答案 2 :(得分:0)

这里的问题是Groovy Strings将通过替换'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