You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nifi运行Groovy脚本拆分CSV数组列报MissingMethodException错误

错误原因

  • takeBetween、takeBefore、takeAfter 属于 Groovy 2.5.0 版本才新增的字符串扩展方法,你运行脚本的环境(常见为 Apache NiFi 这类自带 Groovy 运行环境的工具)的 Groovy 版本低于 2.5.0,而本地 Eclipse 使用的 Groovy 版本高于等于 2.5.0,所以出现本地运行正常、部署后报错的情况。
  • 另外你的代码存在笔误:循环中调用的 row.getAt(i) 没有定义 row 变量,实际应该取拆分后的数组元素。

解决方案

方案1:升级运行环境 Groovy 版本

将脚本运行环境的 Groovy 版本升级到 2.5.0 及以上,即可直接兼容原有写法。

方案2:修改代码兼容低版本 Groovy(无需升级环境,兼容性更强)

将扩展方法替换为正则匹配的原生写法,同时修复笔误、补充表头处理逻辑,完整修改后的代码如下:

def flowFile = session.get()
if(!flowFile) return
try {
flowFile = session.write(flowFile, {inputStream, outputStream ->
    outputStream.withWriter("UTF-8"){ w ->
        def isHeader = true
        inputStream.eachLine("UTF-8"){ line ->
            // 表头直接输出不处理
            if(isHeader) {
                w << line << '\n'
                isHeader = false
                return
            }
            // 正则匹配[]包裹的数组内容
            def matcher = (line =~ /(.*)\[(.*)\](.*)/)
            if(matcher.matches()) {
                def lineBefore = matcher[0][1]
                def arrayContent = matcher[0][2]
                def lineAfter = matcher[0][3]
                // 拆分数组并去除元素前后空格
                def splitArray = arrayContent.split(',').collect{it.trim()}
                splitArray.each { item ->
                    w << lineBefore << item << lineAfter << '\n'
                }
            }else {
                w << line << '\n'
            }
        }
    }
} as StreamCallback)

session.transfer(flowFile, REL_SUCCESS)
}catch(e) {
      log.error('Error capturing nextLink', e)
      session.transfer(flowFile, REL_FAILURE)
}
  • 正则表达式 /(.*)\[(.*)\](.*)/ 实现了原本 takeBetween 等方法的功能,兼容所有 Groovy 2.0 以上版本。
  • 补充了表头跳过逻辑,避免表头被错误处理。
  • 修复了未定义 row 变量的笔误,增加了数组元素去空格处理,避免输出多余空格。

内容的提问来源于stack exchange,提问作者likeGreen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:24:03