The CSV specification (section 2.4. of RFC 4180 ) explicitly states:
Spaces are considered part of a field and should not be ignored.
However, in some cases, you might want to remove leading and trailing spaces from fields while reading a CSV file
or modify the fields in another way (e.g., converting them to lower- or uppercase). FastCSV allows you to do this
using a field modifier that can be used together with a CsvRecordHandler
.
Tip
If you want to read fields not as string but as a specific type (e.g., Boolean
, Long
, LocalDate
, etc.),
you should check out the Custom Callback handler example .
Example
In the following example, fields are modified while reading a CSV file.
import de.siegmar.fastcsv.reader.CsvReader ;
import de.siegmar.fastcsv.reader.CsvRecordHandler ;
import de.siegmar.fastcsv.reader.FieldModifier ;
import de.siegmar.fastcsv.reader.FieldModifiers ;
* Example for reading CSV data from a String while using a field modifier.
public class ExampleCsvReaderWithFieldModifier {
private static final String DATA = " foo , BAR \n FOO2 , bar2 " ;
public static void main ( final String [] args ) {
System . out . println ( " Trim fields: " ) ;
. build ( new CsvRecordHandler ( FieldModifiers . TRIM ) , DATA )
. forEach ( System . out :: println ) ;
System . out . println ( " Combine modifiers (trim/lowercase): " ) ;
. build ( new CsvRecordHandler ( combinedModifier ()) , DATA )
. forEach ( System . out :: println ) ;
System . out . println ( " Custom modifier (trim/lowercase on first record): " ) ;
. build ( new CsvRecordHandler ( customModifier ()) , DATA )
. forEach ( System . out :: println ) ;
private static FieldModifier combinedModifier () {
return FieldModifiers . TRIM
. andThen ( FieldModifiers . lower ( Locale . ENGLISH )) ;
private static FieldModifier customModifier () {
return new FieldModifier () {
public String modify ( final long startingLineNumber ,
return startingLineNumber == 1
? field . trim () . toLowerCase ( Locale . ENGLISH )
You also find this source code example in the
FastCSV GitHub repository .