Monday, December 5, 2011

CSV file parser I/O

@Grab(group = 'net.sf.opencsv', module = 'opencsv', version = '2.3')
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVParser
import au.com.bytecode.opencsv.CSVWriter

String TEST_FILE_NAME = 'C:\\test.csv'
String TEST_OUTPUT_FILE_NAME = 'C:\\testOut.csv'

List< String[] > rows = new CSVReader(
    new FileReader(new File(TEST_FILE_NAME)), 
    CSVParser.DEFAULT_SEPARATOR, 
    CSVParser.DEFAULT_ESCAPE_CHARACTER, 
    CSVParser.DEFAULT_QUOTE_CHARACTER, 1
).readAll()

List< String[] > rowsOver100 = rows.findAll { it[1].toInteger() > 100 }

File output = new File(TEST_OUTPUT_FILE_NAME)
if (output.exists()) {
    output.delete()
}

output.createNewFile()
output.withWriter { writer ->
    new CSVWriter(writer).writeAll(rowsOver100)
}

// for streaming, see also: http://www.groovy-tutorial.org/basic-csv/

No comments:

Post a Comment