Created
February 27, 2014 17:24
-
-
Save bdkosher/9254772 to your computer and use it in GitHub Desktop.
java.io.File extension method for parsing CSV files row-by-row.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Processes file as a CSV, row by row, using the provided closure. An optional starting | |
* row number may be provided to this method, defaulting to 1 (the first row). | |
* | |
* The provided closure can accept one or two arguments, either: | |
* - the row values (String[]) | |
* - the row values (String[]), the current row number (int) | |
* | |
* Currently, only commas are recognized as the separator. Quoted values are handled | |
* thanks to some regex found on stackoverflow.com (need to track down submitter to | |
* give due credit) | |
* | |
* Example usage: | |
* | |
* new File('my.csv').eachCsvRow(2) { cols -> println cols[1] } | |
*/ | |
File.metaClass.eachCsvRow << { int startRow = 1, Closure closure -> | |
delegate.eachLine { line, lineNumber -> | |
if (lineNumber >= startRow) { | |
def cols = line.split(/,(?=([^"]*"[^"]*")*[^"]*$)/) | |
if (closure.parameterTypes.length == 1) { | |
closure.call(cols) | |
} else { | |
closure.call(cols, lineNumber) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment