I have a CSV file in this format RES,2016-02-23_18:01:27
and I want to map the values to a bean which has String
and Calendar
type attributes. While writing the cell processor method, there is method to parse the value into Date
as ParseDate()
. Here this results in an error as the parser is returning Date
object and I have Calendar
object in my bean.
To overcome this, I have created an overloaded setter method in my bean as below:
public void setDate(Date date) {
this.date = new GregorianCalendar();
this.date.setTime(date);
}
Here is my CellParser
method:
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] {
new StrRegEx("\\w{3}"), // string value check
new ParseDate("yyyy-MM-dd_HH:mm:ss"), // date
};
return processors;
}
Is there any native support. I looked at the official site and it's examples. Couldn't able to find references related to Calendar
. If there is no native support from SuperCSV, is this is best way to overcome this problem?
The easiest way is to write your own custom cell processor.
For example, you can chain the following processor after ParseDate
to convert it to a Calendar
.
public class DateToCalendar extends CellProcessorAdaptor implements DateCellProcessor {
public DateToCalendar() {
}
public DateToCalendar(final CellProcessor next) {
super(next);
}
public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
if( !(value instanceof Date) ) {
throw new SuperCsvCellProcessorException(Date.class, value, context, this);
}
Calendar result = Calendar.getInstance();
result.setTime((Date) value);
return next.execute(result, context);
}
}
For example,
final CellProcessor[] processors = new CellProcessor[] {
new StrRegEx("\\w{3}"), // string value check
new ParseDate("yyyy-MM-dd_HH:mm:ss", new DateToCalendar()) // date
};