Validate CSV files in Java

How quote-aware CSV validation works in Java: what it checks, what it changes, a minimal validator, and how validated files hold up after sharing.

Validating a CSV file in Java usually means confirming that a delimited file splits into the records and fields its producer intended before any downstream code trusts it. Most failures come from quoting. A stray double quote, an unclosed quoted field or a comma that was meant to be data can shift every following value into the wrong column without raising an obvious error. This review covers what a quote-aware validator checks, what it changes and does not change, and how the data holds up once it is shared. No benchmarks or tool test results were supplied, so the behavior described here comes from the widely used CSV conventions in RFC 4180 and general Java behavior, not from measured comparisons.

Is Java-side CSV validation the right fit?

For most pipelines that accept CSV from outside sources, the recommendation is to validate structure in Java before parsing values. The main benefit is that malformed quoting is caught at a known line instead of surfacing later as misaligned data. The decisive tradeoff is strictness. A strict validator rejects files that spreadsheet programs open without complaint. A lenient one accepts those files but may split them differently from how their author saw them. You have to choose which failure is cheaper for your use: a rejected file or a silently reinterpreted one.

  • Well suited: imports from partners, exports from other systems, or user uploads where a wrong column assignment has real consequences.
  • Well suited: batch jobs where a clear line-numbered error report is more useful than a partial load.
  • Less suited: one-off files a person will inspect by eye anyway.
  • Less suited: sources that use a non-standard dialect, such as backslash escapes or single-quote enclosures, unless the validator is configured for that dialect.

Keep the raw file as plain text alongside any validated or normalized output when you need an audit trail, when a person must see exactly what was received, or when the data has no real tabular structure. If the content is mostly free text with occasional commas, a line-oriented or tab-separated format, or a format with explicit escaping such as JSON, can avoid quoting problems altogether.

What validation checks and what it changes

Under the RFC 4180 conventions, a field that contains the delimiter, a double quote or a line break must be enclosed in double quotes. A double quote inside such a field is written as two double quotes. A quote-aware validator walks the file character by character and checks that every quoted field opens at the start of a field, closes before the next delimiter or line ending, and contains only doubled quotes. Most validators also check that every record has the same number of fields.

Input line | Fields as intended | Strict result
"Smith, John",42 | Smith, John / 42 | Valid: the comma is inside quotes
"She said ""hi""",ok | She said "hi" / ok | Valid: doubled quotes are escaped literal quotes
She said "hi",ok | Unclear | Flagged: quote inside an unquoted field
"Smith, John,42 | Unclear | Flagged: quoted field is never closed
"Smith" Jr,42 | Unclear | Flagged: text after a closing quote

Pure validation should change nothing. It reads the file and reports problems. The stored characters change only when a tool parses the file and writes it back out, which is normalization rather than validation. Rewriting can alter the quoting style, line endings, character encoding and the presence of a byte order mark, even when every field value is preserved.

Original:   Smith,"Order 17","She said ""hi"""
Rewritten:  Smith,Order 17,"She said ""hi"""

Both lines decode to the same three fields: Smith, Order 17, and She said "hi". The second field loses its quotes because it contains no delimiter, quote or line break, so a writer that quotes only when necessary drops them. The bytes differ even though the meaning does not. That matters if you compare files by checksum or diff the raw text.

Stored content and displayed content also differ. A spreadsheet hides the enclosing quotes and may reinterpret values as it displays them, for example by dropping leading zeros or reading a value as a date. That display is not proof that the file is valid, and a clean-looking sheet can sit on top of a malformed file. Validate the file itself, not what a viewer shows.

Some terms are ambiguous. "CSV" is not a single strict standard. RFC 4180 describes common practice, but many producers use semicolons, tabs, backslash escapes or other variations. "Quote" here means the ASCII double quote unless your dialect says otherwise. Ideas like reversing, mirroring or restyling text do not apply to CSV validation. The one related case is right-to-left text inside a field. An editor may display it in visual order, but the file stores it in logical order, and the validator sees only the stored order. Because the validator compares only ASCII delimiters, quotes and line breaks, it does not split or alter emoji, combining marks or other multi-code-point characters inside fields.

A minimal quote validator in Java

The class below is a small, dependency-free example of a strict structural check. It reports quoting errors and inconsistent field counts with line numbers, and it does not modify the input. It was not run against a test suite for this article, so treat it as a starting point and test it against samples of your own files.

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

public final class CsvQuoteValidator {

    private CsvQuoteValidator() {
    }

    public static List<String> validate(Reader source, char delimiter) throws IOException {
        List<String> problems = new ArrayList<>();
        PushbackReader in = new PushbackReader(source, 1);
        boolean inQuotes = false;
        boolean fieldStart = true;
        boolean afterClosingQuote = false;
        int fieldCount = 1;
        int expectedFields = -1;
        long line = 1;
        long recordLine = 1;
        int c;
        while ((c = in.read()) != -1) {
            char ch = (char) c;
            if (inQuotes) {
                if (ch == '"') {
                    int next = in.read();
                    if (next == '"') {
                        continue; // doubled quote: a literal quote inside the field
                    }
                    if (next != -1) {
                        in.unread(next);
                    }
                    inQuotes = false;
                    afterClosingQuote = true;
                } else if (ch == '\n') {
                    line++;
                }
                continue;
            }
            if (ch == delimiter) {
                fieldCount++;
                fieldStart = true;
                afterClosingQuote = false;
            } else if (ch == '\r' || ch == '\n') {
                if (ch == '\r') {
                    int next = in.read();
                    if (next != '\n' && next != -1) {
                        in.unread(next);
                    }
                }
                expectedFields = checkFieldCount(problems, recordLine, fieldCount, expectedFields);
                line++;
                recordLine = line;
                fieldCount = 1;
                fieldStart = true;
                afterClosingQuote = false;
            } else if (ch == '"') {
                if (fieldStart) {
                    inQuotes = true;
                    fieldStart = false;
                } else {
                    problems.add("Line " + line + ": quote inside an unquoted field or after a closing quote");
                }
            } else {
                if (afterClosingQuote) {
                    problems.add("Line " + line + ": text after a closing quote");
                    afterClosingQuote = false;
                }
                fieldStart = false;
            }
        }
        if (inQuotes) {
            problems.add("Record starting on line " + recordLine + ": quoted field is never closed");
        } else if (!(fieldStart && fieldCount == 1)) {
            checkFieldCount(problems, recordLine, fieldCount, expectedFields);
        }
        return problems;
    }

    private static int checkFieldCount(List<String> problems, long recordLine, int fieldCount, int expectedFields) {
        if (expectedFields == -1) {
            return fieldCount;
        }
        if (fieldCount != expectedFields) {
            problems.add("Record starting on line " + recordLine + ": expected " + expectedFields
                    + " fields, found " + fieldCount);
        }
        return expectedFields;
    }
}

Open the file with an explicit charset rather than the platform default. The call below uses Path.of, which requires Java 11 or later. Files.newBufferedReader reports malformed input for the chosen charset with an exception instead of silently substituting characters, so encoding problems surface separately from quoting problems.

try (Reader reader = Files.newBufferedReader(Path.of("orders.csv"), StandardCharsets.UTF_8)) {
    List<String> problems = CsvQuoteValidator.validate(reader, ',');
    problems.forEach(System.out::println);
}

The snippet has deliberate limits. It treats whitespace between a closing quote and the delimiter as an error, which matches the strict reading of RFC 4180 but rejects some real-world files. It supports only the double quote as the enclosure and has no backslash-escape mode. A blank line in the middle of the file is reported as a short record, while a trailing line break at the end is accepted. Java's UTF-8 decoder does not strip a byte order mark, so a file that starts with one will have an invisible character before its first field. If that field is quoted, the validator flags it. Commons IO's BOMInputStream is one way to remove the mark before validation.

For production work, an established parser such as Apache Commons CSV, OpenCSV or univocity-parsers saves you from maintaining the state machine yourself. These libraries differ in their default dialects and in how leniently they treat malformed quotes, and those defaults can change between versions. Check the documentation for the version you use, and confirm with a few deliberately broken sample files that malformed input actually raises an error rather than being quietly accepted.

Will the data stay readable and usable after sharing?

A file that passes validation can still be read differently elsewhere. Spreadsheet programs may assume a different delimiter depending on regional settings. In locales where the comma is the decimal separator, semicolons are common, and a valid comma-delimited file can open as a single column. Pasting CSV text into a spreadsheet also relies on the application's own splitting rules, which may not match your validator. When the destination is fixed, test one representative file there instead of assuming that one successful import generalizes to every program or version.

Encoding, the byte order mark and line endings decide whether non-ASCII text survives the trip. Some spreadsheet software uses a byte order mark to detect UTF-8, while some command-line tools and parsers treat it as part of the first value. No single choice suits every destination. Decide based on where the file is going, and document the choice.

Escaping affects searching and editing the raw file. A value stored as She said "hi" appears in the file with doubled quotes, so a plain text search for the quoted word with single quotes around it will miss it. Hand edits in a text editor easily break quote balance. Re-run validation after any manual change.

For accessibility, raw CSV is plain text that screen readers can read, but read raw it becomes a stream of values, commas and quotes with no column context. Opened in a spreadsheet or rendered as a proper table, the same data can be navigated by row and column. No assistive-technology tests were supplied for this article, so no claims are made about how any specific screen reader handles either form. If people will read the data through assistive technology, provide a table view or a plain-language summary alongside the file. Validator output should likewise be plain sentences that name the line and the problem, as in the example above.

Quote validation does not make content safe. Spreadsheet programs may run fields that begin with characters such as =, +, - or @ as formulas, a risk known as CSV or formula injection. A file can be structurally valid and still carry such values. If exported files will be opened in spreadsheets, handle this as a separate step.

What this review could not confirm

  • No performance measurements for the validator or any library on large files.
  • No version-specific confirmation of how Apache Commons CSV, OpenCSV or univocity-parsers handle malformed quotes by default.
  • No scoped tests of how particular spreadsheet applications or screen readers handle validated output.
  • No execution results for the example code; it is illustrative and should be tested against your own data.