Skip to content

Modifying input

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.

Example

In the following example, fields are modified while reading a CSV file.

ExampleCsvReaderWithFieldModifier.java
package example;
import java.util.Locale;
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:");
CsvReader.builder()
.build(new CsvRecordHandler(FieldModifiers.TRIM), DATA)
.forEach(System.out::println);
System.out.println("Combine modifiers (trim/lowercase):");
CsvReader.builder()
.build(new CsvRecordHandler(combinedModifier()), DATA)
.forEach(System.out::println);
System.out.println("Custom modifier (trim/lowercase on first record):");
CsvReader.builder()
.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() {
@Override
public String modify(final long startingLineNumber,
final int fieldIdx,
final boolean quoted,
final String field) {
return startingLineNumber == 1
? field.trim().toLowerCase(Locale.ENGLISH)
: field;
}
};
}
}

You also find this source code example in the FastCSV GitHub repository.