CSV

suggest change

CSV (comma-separated values) looks like the simplest file format there is, which is why so much code parses it wrongly. The JDK has no CSV parser. You can write a small correct one yourself, or use a library such as Apache Commons CSV, OpenCSV or Jackson CSV.

Why split(",") breaks

A field may contain the delimiter, as long as the field is quoted:

String line = "Alice,\"Hello, world\",Paris";
String[] parts = line.split(",");
System.out.println(parts.length); // 4, not 3
// [Alice] ["Hello] [ world"] [Paris]

There are more ways it goes wrong:

split is fine for data you produce yourself and know never holds commas, quotes or newlines. For data from anywhere else, use a real parser.

The rules (RFC 4180)

RFC 4180 describes the most common form of CSV:

Files in the wild often stray from these rules: semicolon delimiters (Excel in many European locales), tabs (TSV), a UTF-8 BOM, \ as the escape character, or rows with missing columns.

A small correct parser and writer

The parser below is a state machine that reads one character at a time from a Reader. Because it reads characters rather than lines, quoted line breaks are handled correctly. The Reader must support mark/reset, which BufferedReader and StringReader both do.

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class SimpleCsv {

    /** Reads one record; returns null at end of input. */
    static List<String> readRecord(Reader in) throws IOException {
        List<String> fields = new ArrayList<>();
        StringBuilder field = new StringBuilder();
        boolean inQuotes = false;
        boolean sawAnything = false;

        int c;
        while ((c = in.read()) != -1) {
            sawAnything = true;
            if (inQuotes) {
                if (c == '"') {
                    in.mark(1);
                    int next = in.read();
                    if (next == '"') {
                        field.append('"');          // "" -> literal quote
                    } else {
                        inQuotes = false;            // closing quote
                        if (next != -1) in.reset();
                    }
                } else {
                    field.append((char) c);          // commas and newlines are data
                }
            } else if (c == '"' && field.isEmpty()) {
                inQuotes = true;                     // opening quote
            } else if (c == ',') {
                fields.add(field.toString());
                field.setLength(0);
            } else if (c == '\r') {
                // ignore; the \n that follows ends the record
            } else if (c == '\n') {
                fields.add(field.toString());
                return fields;
            } else {
                field.append((char) c);
            }
        }
        if (inQuotes) throw new IOException("unterminated quoted field");
        if (!sawAnything) return null;
        fields.add(field.toString());                // last line without newline
        return fields;
    }

    static String escape(String value) {
        if (value == null) return "";
        boolean needsQuotes = value.contains(",") || value.contains("\"")
                || value.contains("\n") || value.contains("\r");
        if (!needsQuotes) return value;
        return "\"" + value.replace("\"", "\"\"") + "\"";
    }

    static String toLine(List<String> fields) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fields.size(); i++) {
            if (i > 0) sb.append(',');
            sb.append(escape(fields.get(i)));
        }
        return sb.append("\r\n").toString();
    }

    public static void main(String[] args) throws IOException {
        String csv = "name,quote,city\r\n"
                + "Alice,\"Hello, world\",Paris\r\n"
                + "Bob,\"He said \"\"hi\"\"\",\"New\nYork\"\r\n"
                + "Carol,,\r\n";

        try (Reader in = new StringReader(csv)) {
            List<String> rec;
            while ((rec = readRecord(in)) != null) {
                System.out.println(rec.size() + " " + rec);
            }
        }

        System.out.print(toLine(List.of("Dave", "5'11\" tall", "a,b")));
    }
}

Output:

3 [name, quote, city]
3 [Alice, Hello, world, Paris]
3 [Bob, He said "hi", New
York]
3 [Carol, , ]
Dave,"5'11"" tall","a,b"

This is enough for well-formed RFC 4180 files. A library adds the things you'll eventually want: headers, other dialects, comments, trimming, line numbers in error messages, and fast buffered I/O.

Apache Commons CSV

Apache Commons CSV is small, has few dependencies and is widely used:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.14.1</version>
</dependency>

A CSVFormat describes the dialect. Start from a predefined one (DEFAULT, RFC4180, EXCEL, TDF for tabs, MYSQL, POSTGRESQL_CSV, ...) and adjust it with builder(). Formats are immutable and thread-safe, so define them once as constants. Builder.get() was added in 1.13. On older versions call build(), which still works.

Parsing with a header

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

static final CSVFormat READ_FORMAT = CSVFormat.RFC4180.builder()
        .setHeader()                  // take column names from the first record
        .setSkipHeaderRecord(true)    // don't return the header as a data record
        .setIgnoreSurroundingSpaces(true)
        .setIgnoreEmptyLines(true)
        .get();

static void printOrders(Path file) throws IOException {
    try (Reader in = Files.newBufferedReader(file, StandardCharsets.UTF_8);
         CSVParser parser = READ_FORMAT.parse(in)) {
        System.out.println(parser.getHeaderNames()); // [id, customer, amount, date]
        for (CSVRecord r : parser) {
            System.out.println(r.getRecordNumber() + ": "
                    + r.get("customer") + " " + r.get("amount"));
        }
    }
}

r.get(int) reads a column by index and r.get(String) reads it by header name. A short row (fewer fields than the header) makes get(name) throw IllegalArgumentException. Check r.isConsistent() or r.isSet("name") first if your input can be ragged. To use another delimiter, call setDelimiter(';') on the builder.

Printing

CSVPrinter quotes and escapes only where needed and writes the header for you:

CSVFormat writeFormat = CSVFormat.RFC4180.builder()
        .setHeader("id", "customer", "amount", "date")
        .get();

try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8);
     CSVPrinter printer = new CSVPrinter(out, writeFormat)) {
    printer.printRecord("A-1", "Acme, Inc.", new BigDecimal("1250.00"), LocalDate.of(2026, 1, 15));
    printer.printRecord("A-2", "Bob \"The Builder\"", new BigDecimal("99.95"), LocalDate.of(2026, 2, 3));
}

Produces:

id,customer,amount,date
A-1,"Acme, Inc.",1250.00,2026-01-15
A-2,"Bob ""The Builder""",99.95,2026-02-03

Values are converted with toString(), and null is written as an empty field unless you configure setNullString(...). printRecords(...) writes several rows at once, including straight from a JDBC ResultSet. CSVPrinter accepts any Appendable, so new CSVPrinter(new StringBuilder(), format) builds CSV in memory.

Mapping to records

Commons CSV doesn't bind to objects automatically. A static factory on a record keeps the conversion in one place:

record Order(String id, String customer, BigDecimal amount, LocalDate date) {
    static Order fromCsv(CSVRecord r) {
        return new Order(
                r.get("id"),
                r.get("customer"),
                new BigDecimal(r.get("amount")),
                LocalDate.parse(r.get("date")));
    }
}

try (CSVParser parser = CSVParser.parse(file, StandardCharsets.UTF_8, READ_FORMAT)) {
    List<Order> orders = parser.stream().map(Order::fromCsv).toList();
}

Converting explicitly is a feature: you decide how to handle bad numbers, empty strings and date formats. To report errors usefully, wrap the conversion and include r.getRecordNumber() or parser.getCurrentLineNumber() in the message.

Streaming large files

CSVParser reads lazily. Iterating it or using stream() holds only one record in memory at a time, so a multi-gigabyte file is no problem. Avoid parser.getRecords(), which loads everything into a list.

try (CSVParser parser = CSVParser.parse(file, StandardCharsets.UTF_8, READ_FORMAT)) {
    BigDecimal total = parser.stream()
            .map(r -> new BigDecimal(r.get("amount")))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
}

Keep the stream inside the try block. It reads from the open file, so it can't be returned to a caller after the parser is closed. When writing large output, use a BufferedWriter and call printRecord per row instead of building a big list first.

Encodings and the BOM

Always pass a charset explicitly. Before Java 18 the default charset was platform-dependent.

Excel and many Windows tools write UTF-8 files that start with a byte order mark (U+FEFF). If you don't strip it, it ends up glued to the first header name. The header becomes "\uFEFFid" instead of "id", and r.get("id") fails with a confusing error. Strip it before handing the reader to the parser:

try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
    reader.mark(1);
    if (reader.read() != '\uFEFF') {
        reader.reset();               // no BOM: rewind
    }
    try (CSVParser parser = READ_FORMAT.parse(reader)) {
        // ...
    }
}

If you already depend on Commons IO, BOMInputStream.builder().setInputStream(in).get() does the same at the byte level.

To make Excel open a UTF-8 file with accented characters correctly, write a BOM yourself:

try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    out.write('\uFEFF');
    try (CSVPrinter printer = CSVFormat.EXCEL.print(out)) {
        printer.printRecord("name", "city");
        printer.printRecord("Zoë", "Kraków");
    }
}

Also be careful with spreadsheet formula injection. If a value from an untrusted user starts with =, +, - or @, Excel may run it as a formula when the CSV is opened. When exporting user data meant for spreadsheets, prefix such values with '.

Other libraries

OpenCSV (com.opencsv:opencsv) has a simple array-based API and annotation-based bean binding (@CsvBindByName with CsvToBeanBuilder):

try (CSVReader reader = new CSVReader(Files.newBufferedReader(file))) {
    String[] row;
    while ((row = reader.readNext()) != null) {
        System.out.println(String.join(" | ", row));
    }
}

Jackson CSV (com.fasterxml.jackson.dataformat:jackson-dataformat-csv) is a good choice if you already use Jackson for JSON. It binds rows straight to POJOs and records. LocalDate fields need the jackson-datatype-jsr310 module:

CsvMapper mapper = CsvMapper.builder()
        .addModule(new JavaTimeModule())
        .build();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
try (MappingIterator<Order> it = mapper.readerFor(Order.class)
        .with(schema).readValues(file.toFile())) {
    while (it.hasNext()) {
        Order o = it.next();
    }
}

When writing with mapper.schemaFor(Order.class), columns are ordered alphabetically unless you annotate the class with @JsonPropertyOrder({"id", "customer", "amount", "date"}).

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents