0

我有一个类正在解析基于 csv 的文件,但我想为令牌符号设置一个参数。请让我知道如何更改功能并在程序上使用该功能。

class CSVParser{  
  static def parseCSV(file,closure) {  
        def lineCount = 0
        file.eachLine() { line ->  
            def field = line.tokenize(';')  
            lineCount++  
            closure(lineCount,field)  
        }  
    }  
} 


use(CSVParser.class) {  
    File file = new File("test.csv")  
    file.parseCSV { index,field ->  
        println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"  
    }  
} 
4

2 回答 2

2

您必须在file和参数之间添加closure参数。

当您使用静态方法创建类别类时,第一个参数是调用该方法的对象,因此file必须是第一个。

将闭包作为最后一个参数允许闭包的左大括号跟在没有括号的函数调用之后的语法。

下面是它的外观:

class CSVParser{  
    static def parseCSV(file,separator,closure) {  
        def lineCount = 0
        file.eachLine() { line ->  
            def field = line.tokenize(separator)  
            lineCount++  
            closure(lineCount,field)  
        }  
    }  
} 

use(CSVParser) {  
    File file = new File("test.csv")  
    file.parseCSV(',') { index,field ->  
        println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"  
    }
}
于 2013-01-15T23:10:39.590 回答
1

只需将分隔符作为第二个参数添加到parseCSV方法中:

class CSVParser{  
  static def parseCSV(file, sep, closure) {  
    def lineCount = 0
    file.eachLine() { line ->  
      def field = line.tokenize(sep)  
      closure(++lineCount, field)  
    }  
  }  
} 

use(CSVParser.class) {  
  File file = new File("test.csv")  
  file.parseCSV(";") { index,field ->  
    println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"  
  }  
} 
于 2013-01-15T23:07:53.077 回答