I am currently new and dabbling with groovy. I made a simple function called
parseCsvFile
println
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVParser
def parseCsvFile(String csvFilePath){
if (fileExists(csvFilePath)) {
new File(csvFilePath).withReader { reader ->
CSVReader csvReader = new CSVReader(reader)
csvReader.each { fields ->
println fields
}
}
} else {
throw error
}
//return a key value array
}
GAME_ID,GAME_NAME,OLD_OWNER_NAME,NEW_OWNER_NAME,ORG_NAME
20001,str.git,Gemini,Kitoshi,Blue-DiamondGames
30001,str.git,Kashi,Sensu,FlyingMonkey
Since you are using groovy, you could simple use groovycsv and achieve the same with so simple as shown below:
Example - csv as String
@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv
def csv = """GAME_ID,GAME_NAME,OLD_OWNER_NAME,NEW_OWNER_NAME,ORG_NAME
20001,str.git,Gemini,Kitoshi,Blue-DiamondGames
30001,str.git,Kashi,Sensu,FlyingMonkey"""
def data = parseCsv(csv)
for(line in data) {
println "$line.GAME_ID $line.GAME_NAME"
}
You can also use data from file. Just put the above data in csv file and provide input to FileReader
and pass it to parseCsv
method as shown below:
Example - csv as File
@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv
//Change the filepath as per your environment
def data = parseCsv(new FileReader('/tmp/game.csv'))
for(line in data) {
println "$line.GAME_ID $line.GAME_NAME"
}
Note: You should be able to use column name to refer the data if you notice above println
statement