CSV reader using supercsv in groovy
Following example code hows how to read a CSV using SuperCSV library in groovy
import groovy.util.logging.Slf4j
import org.supercsv.cellprocessor.ift.CellProcessor
import org.supercsv.io.CsvBeanReader
import org.supercsv.io.ICsvBeanReader
import org.supercsv.prefs.CsvPreference
@Slf4j
public class CsvReader {
public static <T> List<T> read(File file, Class<T> clazz, CellProcessor[] processors) {
ICsvBeanReader beanReader = null
int counter = 2
try {
beanReader = new CsvBeanReader(new FileReader(file), CsvPreference.STANDARD_PREFERENCE)
final String[] header = beanReader.getHeader(true)
T reviewJob
List<T> reviewJobList = new ArrayList<T>()
while ((reviewJob = beanReader.read(clazz, header, processors)) != null) {
reviewJobList.add(reviewJob)
counter++
}
return reviewJobList
} catch (Exception e) {
log.error("Error while reading csv at:{}", counter, e)
return null
} finally {
if (beanReader != null) {
try {
beanReader.close()
} catch (IOException e) {
// ignore
}
}
}
}
}