【问题标题】:Trying to split each line by comma Groovy尝试用逗号分隔每一行 Groovy
【发布时间】:2021-08-09 18:03:50
【问题描述】:

我正在尝试在 groovy 中进行一些测试以集成到我的管道中。基本上我想要的是用逗号分隔 csv 文件夹的每一行。 想象一下我在 file1.csv 中有这个内容: 饭,真的,好 意大利面,假,坏 鸡,真的,好的 使用我的 groovy 方法,我想用逗号分隔 csv 并列出食物字符串。 但是,当我尝试打印以查看是否发生拆分时,我会收到一条错误消息。

捕获:org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将具有类“java.lang.String”的对象“D:\Desktop\test\file1.csv”转换为类“groovy.lang.GString”

有人可以帮助我了解我做错了什么吗? 谢谢:)

def test() {
    def mapParts = [:]
    readFile("D:\\Desktop\\test\\file1.csv" as GString).splitEachLine( /,/ )
            { it ->
        println it
    }
}

【问题讨论】:

  • 你为什么不new File("D:\\Desktop\\test\\file1.csv").splitEachLine( /,/ ){ println it }
  • 使用新文件效果很好,谢谢 :) 但为什么我需要使用“新文件”而不是 readFile 来避免出现该错误?只是为了我清楚地理解:)

标签: groovy jenkins-groovy


【解决方案1】:

这应该在普通的 Groovy 中工作:

new File("D:\\Desktop\\test\\file1.csv").splitEachLine( /,/ ){ 
  println it 
}

readFileref-docthis example 的选项需要映射:

readFile(file: "D:\\Desktop\\test\\file1.csv").splitEachLine( /,/ ){ 
  println it 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多