Trim leading and trailing spaces in OpenCSV
java, opencsv, trim
Solution
If you are working with bean mapping and OpenCSV, I personally prefer to extend the MappingStrategy as it handles the final value assignments to their related fields. Imagine your fields are tab separated. Then you might have hard time to extend the CSVReader. Also, less coding is required.
In the following example, I am using a ColumnPositionMappingStrategy but yours can be any other MappingStrategy as populateNewBean is in the parent abstract class.
private <T> MappingStrategy<T> createMappingStrategy() {
return new ColumnPositionMappingStrategy<T>() {
@Override
public T populateNewBean(String[] line) throws CsvDataTypeMismatchException, CsvConstraintViolationException,
CsvRequiredFieldEmptyException, CsvValidationException {
Arrays.setAll(line, (i) -> line[i].trim());
return super.populateNewBean(line);
}
};
}
As you can see, each field/line is trimmed before bean is populated.
Problem
I am using OpenCSV's `CSVReader` to read some comma separated values from a file. I'm not sure how to trim leading and trailing spaces. Sure, I could do `String.trim()` but it would be cleaner not to. In the documentation there is no such option specified.