Groovy replacing place holders of file content similar to multiline-string

醉酒当歌 提交于 2021-02-19 08:09:06

问题


Got the following script which replaces values in the multi line string.

def param1 = 'Groovy'
def param2 = 'Java'
def multiline = """
${param1} is closely related to ${param2},
so it is quite easy to make a transition.
"""
//output shows with the replaced values for param1 and param2
println multiline

Output is shown as expected:

Groovy is closely related to Java,
so it is quite easy to make a transition.

Issue:

Now I am trying to do the same using file instead of multi line string. i.e., copied the multi line string to a file and using the below script to do the same but not working(not giving the desired result).

I am sure, it must be something I am missing. Tried multiple way, but went futile.

Try #1: Script

def param1 = 'Groovy'
def param2 = 'Java'
def multiline = Eval.me(new File('test.txt').text)
println multiline

And it fails to run. Error follows:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script1.groovy: 1: expecting EOF, found ',' @ line 1, column 42. s closely related to ${param2}, ^
1 error

Try #2

def param1 = 'Groovy'
def param2 = 'Java'
def multiline = new File('test.txt').text
def finalContent = """$multiline"""
println finalContent

And there is no difference in the output, just showing the file content as it is.

Output:

${param1} is closely related to ${param2},
so it is quite easy to make a transition.

Any pointers what am I missing?

Please note that at the moment I want to avoid file content modification using replace() method.


回答1:


Not sure why it doesn't work, however what I may suggest here is that templating suits best here. Please have a look:

import groovy.text.SimpleTemplateEngine

def f = new File('lol.txt')
println f.text

def binding = [
    param1: 'Groovy',
    param2: 'Java',
]

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

println template.toString()

An explanation why file content is not evaluated may be found here.



来源:https://stackoverflow.com/questions/38046210/groovy-replacing-place-holders-of-file-content-similar-to-multiline-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!