opencsv.utils.CsvMapper Maven / Gradle / Ivy
package opencsv.utils;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import au.com.bytecode.opencsv.bean.CsvToBean;
import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.*;
import static au.com.bytecode.opencsv.CSVWriter.DEFAULT_SEPARATOR;
import static au.com.bytecode.opencsv.CSVWriter.NO_QUOTE_CHARACTER;
public class CsvMapper implements ICsvMapper {
private final Map columnMapping = new HashMap();
private final HashMap fieldMap = new HashMap();
private final Class type;
public CsvMapper(Class type) {
this.type = type;
}
@Override
public ICsvMapper withMapping(Map mapping) {
this.columnMapping.putAll(mapping);
return this;
}
@Override
public ICsvMapper withMapping(ICsvColumnMapping mapping) {
return withMapping(mapping.getColumnMapping());
}
@Override
public ICsvMapper withMapping(String header, String property) {
this.columnMapping.put(header, property);
return this;
}
@Override
public List fromCsv(Reader reader) {
HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
strategy.setType(type);
strategy.setColumnMapping(columnMapping);
List list = new ArrayList();
try {
list = new CsvToBean().parse(strategy, new CSVReader(reader));
} catch (Exception ex) {
throw new CsvMapperRuntimeException(ex);
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (Exception ex) {
throw new CsvMapperRuntimeException("Close the reader failed.", ex);
}
}
}
return list;
}
@Override
public void toCsv(Writer writer, List list) throws Exception {
CSVWriter csvWriter = new CSVWriter(writer, DEFAULT_SEPARATOR, NO_QUOTE_CHARACTER);
final List lines = new ArrayList();
for (T item : list) {
lines.add(getLine(item));
}
csvWriter.writeNext(columnMapping.keySet().toArray(new String[0]));
csvWriter.writeAll(lines);
csvWriter.flush();
}
private String[] getLine(T item) throws Exception {
final List list = new ArrayList();
for (String key : columnMapping.keySet()) {
if (!fieldMap.containsKey(key)) {
final String fieldName = columnMapping.get(key);
fieldMap.put(key, item.getClass().getDeclaredField(fieldName));
}
Field field = fieldMap.get(key);
field.setAccessible(true);
final Object value = field.get(item);
list.add(value == null ? "" : value.toString());
}
return list.toArray(new String[0]);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy