Convert field values with OpenCSV

How OpenCSV converters change CSV and TSV field values in Java, when a custom converter fits, what changes in the data, and how to keep output usable.

OpenCSV is a Java library for reading and writing delimited text such as CSV and TSV. When it maps rows to Java objects (beans), it has to turn each text field into a typed value, and turn typed values back into text when writing. A converter controls that step. This review explains what an OpenCSV converter actually changes, when a custom converter is worth writing, and what to check so the converted data stays readable and usable once it leaves your program.

Evidence note: no version-specific documentation excerpts, benchmarks or test results were supplied for this article. The descriptions below reflect OpenCSV's general, publicly documented design. Class signatures and supported types have changed between major versions, so confirm details against the documentation for the version you use.

Clarifying the term "converter"

Searches for an "opencsv converter" can mean two different things. Some people want a tool that converts a whole file, for example CSV to JSON or CSV to TSV. Others want to control how individual field values are parsed into Java types. OpenCSV's converter concept is the second: it works at the level of a single field in a bean. Changing the separator from comma to tab is not a converter task; it is a parser and writer setting.

Is a custom converter suitable for your use?

Recommendation: use OpenCSV's built-in annotations first, and write a custom converter only when a field's text format does not map cleanly onto a standard Java type. The main benefit of a custom converter is that conversion rules live in one tested class instead of being scattered through post-processing code. The decisive tradeoff is that the converter becomes part of your data contract: if it is lossy or one-directional, values can no longer be written back in their original form.

  • A custom converter tends to fit when:
  • The source uses domain-specific tokens, such as yes/no, Y/N or status codes, that should become a boolean or enum.
  • A value must be validated and rejected with a clear error rather than silently accepted.
  • The same column format appears in several files and should be handled consistently.
  • You need reading and writing to be symmetric, with a defined output format.
  • Keeping the field as a plain String is preferable when:
  • You are only passing the file through, filtering rows or changing delimiters.
  • The exact original text matters for auditing, legal records or reproducibility.
  • The format is inconsistent enough that a strict converter would reject many rows you still need.
  • Downstream consumers expect the original text and would be affected by normalization.

What a converter actually changes

A converter changes stored data, not presentation. On read, the text in a field is replaced in your bean by a typed Java object. On write, the typed object is turned back into text. Nothing about how the CSV file looks in an editor is altered by the converter itself; what changes is the value your program holds and the text it later writes.

OpenCSV offers several levels of control:

Mechanism | What it does | Typical use
@CsvBindByName / @CsvBindByPosition | Default conversion of text to common types such as numbers, booleans and strings | Straightforward columns
@CsvDate | Parses and formats dates using a pattern you supply | Date and time columns with a known format
@CsvNumber | Parses and formats numbers using a decimal pattern | Numbers with fixed precision or grouping
locale attribute on binding annotations | Applies locale rules when parsing or formatting | Decimal commas or locale-specific formats
@CsvCustomBindByName / @CsvCustomBindByPosition | Delegates conversion to your own class | Domain-specific formats and validation

A custom converter extends AbstractBeanField. In recent major versions it takes two type parameters: the bean type and the index type (String for header-based binding, Integer for position-based binding). You implement convert for reading and can override convertToWrite for writing; if you do not override it, writing falls back to a default text representation, which may not match the original input format.

Illustrative example: yes/no to Boolean

The following converter maps "yes" and "no" to Boolean values, treats an empty field as null, and rejects anything else. It is illustrative and has not been tested against a specific OpenCSV release here.

public class YesNoConverter extends AbstractBeanField<Order, String> {

    @Override
    protected Object convert(String value) throws CsvDataTypeMismatchException {
        if (value == null || value.isBlank()) {
            return null;
        }
        switch (value.trim().toLowerCase(Locale.ROOT)) {
            case "yes": return Boolean.TRUE;
            case "no":  return Boolean.FALSE;
            default:
                throw new CsvDataTypeMismatchException(
                        value, Boolean.class, "Expected yes or no");
        }
    }

    @Override
    protected String convertToWrite(Object value) {
        if (value == null) {
            return "";
        }
        return ((Boolean) value) ? "yes" : "no";
    }
}

Checking the example against the mechanism: an input of "Yes " becomes Boolean.TRUE because the value is trimmed and lower-cased before matching. On write it becomes "yes", not "Yes ". That is a real change to the stored text: capitalization and trailing spaces are not preserved. If the original form matters, this converter is lossy for your purpose.

Binding the converter and reading a TSV file

public class Order {

    @CsvBindByName(column = "id")
    private String id;

    @CsvCustomBindByName(column = "paid", converter = YesNoConverter.class)
    private Boolean paid;

    @CsvBindByName(column = "order_date")
    @CsvDate("yyyy-MM-dd")
    private LocalDate orderDate;

    // getters and setters
}

try (Reader in = Files.newBufferedReader(Path.of("orders.tsv"), StandardCharsets.UTF_8)) {
    CSVReader reader = new CSVReaderBuilder(in)
            .withCSVParser(new CSVParserBuilder().withSeparator('\t').build())
            .build();

    CsvToBean<Order> csvToBean = new CsvToBeanBuilder<Order>(reader)
            .withType(Order.class)
            .withThrowExceptions(false)
            .build();

    List<Order> orders = csvToBean.parse();
    List<CsvException> problems = csvToBean.getCapturedExceptions();
}

Two points in this example matter for suitability. The separator is a parser setting, independent of the converter. And withThrowExceptions(false) collects conversion errors instead of stopping at the first bad row, which lets you decide whether rejected rows are acceptable. Whether java.time types such as LocalDate are supported by @CsvDate depends on your OpenCSV version; older versions targeted java.util.Date.

Will the converted data remain usable after sharing?

Because CSV and TSV are plain text, usability after sharing depends on the text your writer produces, not on the Java types in between. The main risks are format drift and silent loss rather than unreadable characters.

  • Round-trip fidelity: read a sample file, write it back, and compare. Any difference shows exactly what your converters normalize or drop.
  • Dates and numbers: patterns and locale settings decide whether output reads as 1,5 or 1.5 and which date order appears. A file written with one locale can be misread by a consumer that assumes another.
  • Encoding: specify the character set explicitly on both reader and writer. Relying on the platform default can corrupt non-ASCII text when files move between systems.
  • Headers and column order: when writing beans by header name, OpenCSV's default mapping strategy has historically produced upper-cased header names in a sorted order rather than the original layout. Verify this in your version and supply an explicit column order if consumers depend on it.
  • Empty versus missing: decide whether an empty field becomes null, an empty string or a default, and make sure convertToWrite reverses that choice consistently.

Opening the output in a spreadsheet application is a common check, but a single successful rendering does not show that every destination will interpret dates, leading zeros or decimal separators the same way. No scoped tests of specific spreadsheet applications or import tools were supplied for this article, so treat compatibility with any named destination as something to verify with your own sample files.

Accessibility and assistive technology are rarely affected by the converter itself, since the output remains ordinary text in a predictable column order. Any accessibility concerns usually arise later, in how a spreadsheet or report presents the data, which is outside OpenCSV's scope.

When to keep a plain-text equivalent

If a converter normalizes, trims or rejects values, consider keeping the original text alongside the converted value, either as an extra String field bound to the same column through a separate pass or by archiving the source file unchanged. This is especially useful when the data may be audited, when conversion rules may change later, or when rejected rows need to be reviewed by a person. For outputs meant to be read by other systems, unambiguous formats such as ISO-style dates and dot decimal separators reduce interpretation errors.

Bottom line

OpenCSV's converters are a good fit when you need typed, validated field values and consistent rules across files. Start with the built-in date, number and locale options, add a custom converter only for formats they cannot express, and always define the write direction so data can be exported in a predictable form. Where the exact original text matters, or where formats are too inconsistent for strict parsing, keep the field as plain text and convert later.