Parse CSV file with Groovy

peterchen-easyli發表於2013-10-25
#!/usr/bin/groovy

class CsvParser {
    static void parse(String filePath, Closure closure) {
        File file = new File(filePath)
        file.eachLine() {line ->
            def fields = line.split(";")
            closure(fields)
        }
    }
    static void usage(String name) {
        println "${name} <csv file>" 
    }

    static void main(String[] args) {
        if (args.size() < 1) {
            usage(CsvParser.getProtectionDomain().getCodeSource().getLocation().getPath())
            return
        }

        parse(args[0]){fields ->
            def i =0
            for (field in fields) {
                print "[${i}]" + field + " "
                i++
            }
            println ""
        }
    }
}

相關文章