Quick revision
The short answer
CSV is not just values separated by commas: a field can be wrapped in quotes and then contain commas, doubled quotes and even line breaks, and line.split(",") knows nothing about quoting, so an address like "Main St, Apt 4" becomes two columns and everything after it shifts. We replace split with a real CSV parser such as Apache Commons CSV, FastCSV, OpenCSV or Jackson's CSV module, read the file as a stream with an explicit charset and BOM handling, and validate each record's column count, reporting bad lines with their line numbers instead of failing the whole job.
What to remember
In this answer, we saw that CSV fields can be quoted and contain commas, doubled quotes and line breaks, so split(",") shifts columns and leaves quotes in values. A real parser such as Commons CSV, FastCSV, OpenCSV or Jackson's CSV module handles RFC 4180 and streams records. The job was slow because non-trivial split arguments compile a regex on every call and because files were loaded whole and rows inserted one by one. We read with an explicit charset, handle the byte order mark, stream records, batch inserts, and validate each record with line numbers instead of failing the whole job.
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.
CSV is not just values separated by commas: a field can be wrapped in quotes and then contain commas, doubled quotes and even line breaks, and line.split(",") knows nothing about quoting, so an address like "Main St, Apt 4" becomes two columns and everything after it shifts. We replace split with a real CSV parser such as Apache Commons CSV, FastCSV, OpenCSV or Jackson's CSV module, read the file as a stream with an explicit charset and BOM handling, and validate each record's column count, reporting bad lines with their line numbers instead of failing the whole job.
Why this question is asked
Importing CSV files is one of those jobs that seems finished after an afternoon and then produces bug reports for years. The first version almost always uses split, and it works on the test file. Then real customer data arrives, with commas inside addresses, quotes inside names and files of tens of millions of lines. Interviewers like this scenario because it mixes a correctness bug, a performance problem and an operational question about bad data. In this answer, we will see what CSV really allows, reproduce the column shift, replace split with a proper parser, look at why the job is slow and how to read the file correctly, and finally handle bad records without stopping the import.
1What CSV Really Allows
CSV has a specification, RFC 4180, and most tools that write CSV, such as Excel and database exports, follow it closely. The rules that matter here are about quoting. A field that contains the separator, a quote or a line break is wrapped in double quotes. Inside a quoted field, a double quote is written twice. And a quoted field may span more than one physical line.
This one record has three fields: 42, then Main St, Apt 4, then Ana "Bee" Diaz. The commas and quotes inside the quoted fields are data, not structure. To read it correctly, a parser must remember whether it is currently inside quotes, which is state that a simple split cannot have.
2Reproducing the Column Shift
split(",") cuts at every comma, including the one inside the address. Let us see what the job actually receives.
Every column after the address is now shifted by one, so the name lands in the wrong field, and the quotes remain in the values because split does not remove them either. If a field contains a line break, it is worse: the reader returns half a record as one line and the rest as the next. People sometimes try a clever regex with a lookahead that only splits on commas outside quotes, but it rescans the rest of the line at every comma, which is slow on long lines, and it still cannot join records broken across lines.
3Use a CSV Parser Instead
Several mature libraries implement RFC 4180 and stream records one at a time: Apache Commons CSV, FastCSV, OpenCSV and Jackson's CSV data format module. Any of them is a good choice; the important thing is to stop parsing CSV by hand. Here is the shape with Commons CSV.
The parser handles quotes, doubled quotes and line breaks inside fields, and it gives back clean values without the surrounding quotes. Because it reads from a Reader and returns records lazily, memory stays flat whatever the size of the file. We can configure the format for a header row, a different delimiter or trimming through CSVFormat's builder (check the method names for your library version).
4Why the Job Is Slow on 50 Million Lines
Part of the slowness is split itself, and the reason is a detail of its implementation. When the argument is a single character that is not a regex metacharacter, such as a comma, String.split takes a fast path that does not use the regex engine at all. For any other argument, such as ";\\s*" or "\\|", it calls Pattern.compile on every call, so 50 million lines mean 50 million pattern compilations, plus an array and new strings for every line.
The other usual causes are reading the whole file into memory with Files.readAllLines, which fills the heap and makes the garbage collector work hard, and writing to the database one row at a time. A streaming parser fixes the first, and batching inserts, for example 1,000 rows per JDBC batch or PostgreSQL's COPY, fixes the second. With those in place, parsing 50 million lines is typically a matter of minutes rather than hours.
5Reading the File Correctly
Before parsing, we must turn bytes into characters, and that needs the right charset. new FileReader(file) without a charset uses the platform default (UTF-8 by default since Java 18, but something else on older JVMs and some systems), so we always name it. Files exported from Excel often start with a byte order mark, the invisible character U+FEFF, which then sticks to the first header name, so a column called id is read as a BOM followed by id and lookups by name fail. Commons IO's BOMInputStream removes it, or we strip U+FEFF from the first value ourselves.
- Open a stream with an explicit charsetUTF-8 unless the customer says otherwise
- Skip the byte order mark if presentU+FEFF at the very start
- Parse one record at a timeCommons CSV, FastCSV, OpenCSV, Jackson
- Column count as expected?YesValidate and convert the valuesNoRecord line number and reason, continue
- Insert in batchesfor example 1,000 rows per batch
- Too many bad records?YesStop and report the fileNoFinish and publish the error report
6 steps in order. Play them, or step through them one at a time.
6Validating Each Record Instead of Failing the Job
In a large file from a customer, some records will be wrong. Failing the whole job on the first bad line means one typo blocks millions of good rows, and the customer learns nothing useful. Instead, we check every record: the right number of columns, required fields present, values that parse as numbers or dates. A good record is imported; a bad one is written to an error report with its record number, physical line number and the reason, such as expected 3 columns but found 4.
We also set a threshold, for example more than 1 percent bad records, above which the job stops and reports the file as a whole, because at that rate the file is probably in the wrong format rather than containing a few typos. The error report goes back to the customer, who can fix the source and resend only those lines.
7Follow-up questions
How would you handle a file whose delimiter changes between customers?
I would make the delimiter part of each customer's import configuration, stored with the customer and chosen when the integration is set up, and build the CSVFormat from that configuration, for example with a semicolon for many European exports, which also use the comma as a decimal separator. Guessing the delimiter from the content is fragile, so I would only use detection as a helper at setup time: count candidate characters in the header line, propose one, and let a person confirm it. The job then validates that the header has the expected columns, which catches a wrong delimiter on the first line instead of a million lines later.
Could a regex split CSV correctly?
For single-line records, a pattern that splits on commas followed by an even number of quotes can work, but it rescans the rest of the line at every comma, so it is quadratic in the line length, and it still leaves the surrounding and doubled quotes to clean up. It also cannot handle a field with a line break, because the record arrives as two lines. A CSV parser is a small state machine that does all of this in one pass, so there is no reason to maintain a fragile regex.
How do you test the new import?
With a set of small files that each contain one tricky case: a quoted comma, a doubled quote, a line break inside a field, an empty last field, a BOM, a wrong column count and a non-UTF-8 file. Each test asserts the exact values read and the exact errors reported. Then we run one large generated file to measure throughput and memory, so a regression in speed is noticed as well as a regression in correctness.
8Conclusion
In this answer, we saw that CSV fields can be quoted and contain commas, doubled quotes and line breaks, so split(",") shifts columns and leaves quotes in values. A real parser such as Commons CSV, FastCSV, OpenCSV or Jackson's CSV module handles RFC 4180 and streams records. The job was slow because non-trivial split arguments compile a regex on every call and because files were loaded whole and rows inserted one by one. We read with an explicit charset, handle the byte order mark, stream records, batch inserts, and validate each record with line numbers instead of failing the whole job.
Open with
The core problem is that CSV is not comma-separated text in the simple sense. Under RFC 4180, a field containing a comma, a quote or a line break is wrapped in quotes, quotes inside are doubled, and a quoted field can span lines. split doesn't know about quoting, so Main St comma Apt 4 becomes two fields, every column after it shifts, and quotes stay in the values.
Then, if they want more
So I would replace split with a real parser, like Apache Commons CSV, FastCSV, OpenCSV or Jackson's CSV module, which handle all of that and stream one record at a time.
On performance: split with a single plain character uses a fast path, but any other separator compiles a regex on every call, which on 50 million lines adds up; if you must split, precompile the Pattern.
More often the real costs are reading the whole file into memory and inserting rows one at a time, so I stream records and batch the inserts, or use COPY on PostgreSQL.
I would also read with an explicit charset rather than the platform default, and strip the byte order mark that Excel exports put at the start, otherwise the first header name doesn't match.
Finally, I validate every record, column count, required fields and types, write bad ones to an error report with the record and line number and the reason, keep importing the good ones, and stop the job only if the error rate passes a threshold like one percent.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "An import job parses CSV lines with line.split(","). Customers report wrong columns for...": https://scrivio-interview-library.netlify.app/java/strings/7f9a52358e/