【发布时间】:2021-05-31 11:28:24
【问题描述】:
我需要使用 Groovy 复制“模板”文件并用当前值替换一些文本(变量),然后将文件保存在新文件中。
bay_equipment.each{
hname="Network-${it['hostname']}-${it['function']}"
nodeName="${it['hostname']}"
nodeIP="${it['ip_address']}"
fname="${it['hostname']}-${it['function']}-Network.cfg"
def src= new File("../config-files/nagios-switch-bayg20.cfg")
def dst= new File("../dest-files/$fname")
dst << src.text
//一切顺利
//现在正在尝试打开 dst 文件并进行修改然后保存。
//这个字符串--需要替换为hname变量,同样替换为nodeIP
dst = (dst =~ /<%=@deviceType%>-<%=@deviceGroup%>-<%=@nodeName%>/).replaceFirst("$hname")
dst = (dst =~ /<%=@nodeIP%>/).replaceFirst("$nodeIP")
dst.write(dst)
}
我在运行时遇到错误:
捕获:groovy.lang.MissingMethodException:没有方法签名:java.lang.String.write() 适用于参数类型:(字符串)值:[../dest-files/u100en00700-BAYG20-Network.配置文件] 可能的解决方案:wait()、wait(long)、with(groovy.lang.Closure)、trim()、size()、toSet() groovy.lang.MissingMethodException:没有方法签名:java.lang.String.write() 适用于参数类型:(字符串)值:[../dest-files/u100en00700-BAYG20-Network.cfg] 可能的解决方案:wait()、wait(long)、with(groovy.lang.Closure)、trim()、size()、toSet() 在 nsr_nagios$_run_closure4.doCall(nsr_nagios:53) 在 nsr_nagios.run(nsr_nagios:38)
【问题讨论】:
-
你有什么问题?
-
将替换内容和写入文件的部分分开(例如将源读入字符串,操作字符串,最后写入字符串)。到目前为止,您正在将“dst the file”转换为“dst the string”。
标签: groovy