Quick revision
The short answer
We build a CSVFormat from CSVFormat.DEFAULT with setHeader() and setSkipHeaderRecord(true), so the first line becomes the column names, then open a UTF-8 reader and a CSVParser in try-with-resources and turn each CSVRecord into a record with r.get("customer_id"), r.get("name") and new BigDecimal(r.get("amount")). The parser understands quoted fields such as "Smith, John", so we never split lines on commas ourselves. We strip a UTF-8 BOM from files saved by Excel, and because the parser streams records, memory stays low for large files.
What to remember
In this answer, we parsed a CSV file with Apache Commons CSV. We built a CSVFormat from DEFAULT with setHeader() and setSkipHeaderRecord(true), opened a UTF-8 reader and a CSVParser in try-with-resources, and mapped each CSVRecord by header name into a record with a BigDecimal amount. The parser handles quoted fields with commas, escaped quotes and line breaks, which splitting on commas never can. We skipped the UTF-8 BOM that Excel writes, reported conversion errors with record numbers, and kept memory low by processing records as a stream.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We build a CSVFormat from CSVFormat.DEFAULT with setHeader() and setSkipHeaderRecord(true), so the first line becomes the column names, then open a UTF-8 reader and a CSVParser in try-with-resources and turn each CSVRecord into a record with r.get("customer_id"), r.get("name") and new BigDecimal(r.get("amount")). The parser understands quoted fields such as "Smith, John", so we never split lines on commas ourselves. We strip a UTF-8 BOM from files saved by Excel, and because the parser streams records, memory stays low for large files.
Why this question is asked
CSV looks like the simplest format there is, which is exactly why it causes so many bugs. Splitting each line on commas works in the first test and breaks on the first customer called Smith, John, on the first comment with a line break inside, or on the invisible byte that Excel puts at the start of the file. Interviewers ask this coding question to see whether we know how CSV really works and how to use a proper parser. In this answer, we will recap the CSV rules, see why splitting on commas fails, write the parser with Commons CSV, handle the BOM, and convert rows safely while keeping memory low.
1A Quick Recap of the CSV Rules
CSV, comma-separated values, is described by RFC 4180, though many programs bend it. Each record is a line, fields are separated by commas, and the first line is often a header with the column names. The important part is quoting: a field that contains a comma, a double quote or a line break is wrapped in double quotes, and a double quote inside such a field is written twice.
So the line 42,"Smith, John","He said ""hi""" has exactly three fields: 42, Smith, John, and He said "hi". A quoted field may even contain a line break, which means one CSV record can span two physical lines in the file.
2Why Splitting on Commas Fails
Here is the code every project writes once, and the input that breaks it.
The split has no idea about quotes, so the comma inside the name becomes a field separator, every later column shifts by one, and the amount column now holds part of a name. A line break inside a quoted field is worse: reading line by line cuts the record in half. Handling all the cases correctly is exactly what a CSV library does, so we use one.
3Parsing With Commons CSV
Apache Commons CSV reads records through a CSVFormat, which describes the dialect: separator, quote character, header handling. CSVFormat.DEFAULT follows RFC 4180. setHeader() with no arguments tells the parser to read the column names from the first record, and setSkipHeaderRecord(true) makes sure that record is not returned as data.
- Open the file as UTF-8
Files.newBufferedReader - Does it start with a BOM?YesSkip it with BOMInputStreamNoRead as is
- CSVParser reads one recordhandles quotes, escaped quotes, line breaks
- Look up fields by header namecustomer_id, name, amount
- Do the values convert?YesAdd the RowNoRecord an error with the line number
- Next record until the endonly one record in memory at a time
6 steps in order. Play them, or step through them one at a time.
Notice that we read fields by header name rather than position, so the code keeps working if a partner adds a column or changes the order, and that the reader and the parser are both closed by try-with-resources. The charset is explicit: Files.newBufferedReader defaults to UTF-8, but writing it states the contract. Builder method names have changed across Commons CSV versions (for example build() and get()), so check them for your version.
4The Invisible BOM From Excel
When Excel saves a file as CSV UTF-8, it writes a byte order mark, BOM, at the very start: the character U+FEFF, encoded as three bytes. It is invisible in most editors, but Java does not remove it when decoding UTF-8. So the first header is not customer_id but U+FEFF followed by customer_id, and the lookup by name fails with an error that looks impossible.
BOMInputStream from Commons IO detects and skips the BOM if present and does nothing otherwise, so the same code handles files from Excel and from other programs. Without Commons IO, we can read the first character and skip it if it equals U+FEFF.
5Converting Values and Keeping Memory Low
new BigDecimal(r.get("amount")) is the right type for money, but it is strict: 1,234.50 with a thousands separator or 19,99 with a decimal comma throws NumberFormatException. Rather than letting one bad row stop the import, we catch conversion errors per record and collect them with r.getRecordNumber() or the parser's line number, so the user learns that record 1,204 has an invalid amount.
CSVParser reads one record at a time from the reader, so it streams. The example above collects all rows into a list, which is fine for a few thousand; for a file with millions of rows we process each record as we read it, for example by adding it to a batch insert of 1,000 rows, and memory stays the same whatever the file size.
6Follow-up questions
How does Commons CSV handle a line break inside a quoted field?
It keeps reading until the closing quote, so the field contains the line break and the record continues on the next physical line. That is why getRecordNumber() and the file's line number can differ, and why reading the file line by line before parsing would break such records.
What if the header names differ in case or have spaces?
With setTrim(true) surrounding spaces are removed from values, and recent versions also have options for header handling such as ignoring header case (check the builder methods in your version). It is often clearer to validate the header against the expected names first and fail with a clear message listing what was found.
When would you choose OpenCSV instead?
OpenCSV can bind rows directly to bean classes with annotations, which saves mapping code for many columns. Commons CSV is smaller and lower level, which suits code that wants explicit control over parsing and conversion, as here with records and BigDecimal.
7Conclusion
In this answer, we parsed a CSV file with Apache Commons CSV. We built a CSVFormat from DEFAULT with setHeader() and setSkipHeaderRecord(true), opened a UTF-8 reader and a CSVParser in try-with-resources, and mapped each CSVRecord by header name into a record with a BigDecimal amount. The parser handles quoted fields with commas, escaped quotes and line breaks, which splitting on commas never can. We skipped the UTF-8 BOM that Excel writes, reported conversion errors with record numbers, and kept memory low by processing records as a stream.
Open with
I'd never split lines on commas, because a quoted field like Smith comma John breaks it, and quoted fields can even contain line breaks. With Commons CSV I build the format from CSVFormat.DEFAULT, which follows RFC 4180, with setHeader() and no arguments so the first line provides the column names, and setSkipHeaderRecord(true) so it isn't returned as data; I'd also trim and ignore empty lines.
Then, if they want more
Then in try-with-resources I open a buffered reader with an explicit UTF-8 charset and call format.parse to get a CSVParser, and iterate its CSVRecords. For each one I create a record, Row, with r.get of customer_id and name, and new BigDecimal of the amount, reading by header name so column order doesn't matter.
Files saved by Excel often start with a UTF-8 byte order mark, which makes the first header U+FEFF plus customer_id, so the lookup fails; I'd wrap the input in Commons IO's BOMInputStream to skip it. I'd catch number format errors per record and report them with the record number rather than failing the whole file.
And since the parser streams records, for large files I'd insert in batches instead of collecting a list, so memory stays flat.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Parse a CSV file with header customer_id,name,amount using Apache Commons CSV, handling...": https://scrivio-interview-library.netlify.app/java/document-libraries/cbd6d36c0c/