Groovy如何读取文件并解析文件内容中的变量?

4

我是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)

为什么它会抱怨一个属性,当我什么也没做?我还尝试过在Groovy中使用Java String.replace()中的"\$\{random_id\}",但不起作用。


错误看起来是正确的。我在您发布的代码中没有看到名为random_id的属性,但我看到了一个名为randomId的属性。确实缺少random_id属性 :) - ubiquibacon
问题在于我并没有尝试检索名为random_id的属性的值。 - Shinta Smith
3个回答

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()

3

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

太棒了,@MichaelEaster。这个方法可行!感谢您的建议。 - Shinta Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接