MaryCoding MaryCoding - 8 months ago 82
Groovy Question

Parsing CSV file and creating a key value pair

I am currently new and dabbling with groovy. I made a simple function called

parseCsvFile
. This function reads from a CSV file. However, when I try to
println
I don see the values but instead
import au.com.bytecode.opencsv.CSVReader
. My ultimate goal is to read the csv file and create a key value pair based in the data. How could I best accomplish that?

Function for parsing:

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
}


Example of 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

Rao Rao
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download