io.robe.convert.csv.CSVImporter Maven / Gradle / Ivy
The newest version!
package io.robe.convert.csv;
import io.robe.convert.common.Importer;
import io.robe.convert.common.OnItemHandler;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class CSVImporter extends Importer {
private CsvPreference preference = null;
private Collection fields = null;
private String[] fieldNames = null;
private CellProcessor[] processors = null;
public CSVImporter(Class dataClass) {
this(dataClass, CsvPreference.EXCEL_PREFERENCE.STANDARD_PREFERENCE);
}
public CSVImporter(Class dataClass, CsvPreference preference) {
super(dataClass);
this.preference = preference;
this.fields = getFields(getDataClass());
this.fieldNames = new String[fields.size()];
this.processors = CSVUtil.convertFieldsToCellProcessors(this.fields, this.fieldNames);
}
@Override
public List importStream(InputStream inputStream) throws Exception {
return importStream(inputStream, DEFAULT_ENCODING);
}
@Override
public List importStream(InputStream inputStream, String charSetName) throws Exception {
final List list = new LinkedList<>();
DefaultOnItemHandler handler = new DefaultOnItemHandler(list);
try {
this.importStream(inputStream, handler, charSetName);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@Override
public void importStream(InputStream inputStream, OnItemHandler handler) throws Exception {
this.importStream(inputStream, handler, DEFAULT_ENCODING);
}
@Override
public void importStream(InputStream inputStream, OnItemHandler handler, String charSetName) throws Exception {
Reader reader = new InputStreamReader(inputStream, charSetName);
ICsvBeanReader csvBeanReader = new CsvBeanReader(reader, this.preference);
Object obj;
while ((obj = csvBeanReader.read(getDataClass(), this.fieldNames, this.processors)) != null) {
handler.onItem(obj);
}
}
}