Reference · Article

How to read a CSV file in Java | with examples

Read a CSV file in Java the right way: explicit UTF-8 decoding, Apache Commons CSV 1.14.1 by header name, rows mapped to Java 25 records, the Excel byte order mark fix, writing CSV with CSVPrinter, and a library comparison.

Key Takeaways

  • Use Apache Commons CSV (1.14.1) for any file that can contain quoted commas, doubled quotes or line breaks inside a field. BufferedReader and Scanner read physical lines, not CSV records.
  • Always open the file with an explicit charset, normally Files.newBufferedReader(path, StandardCharsets.UTF_8), and close the reader and parser with try-with-resources.
  • Map each CSVRecord to a Java record and put the record number in every error message, so a bad row in a 200,000-line import is findable.
  • Excel's "CSV UTF-8" export commonly starts with a byte order mark and, in many European locales, uses semicolons. Strip the mark and set the delimiter explicitly.
  • Iterate or stream records for large files. getRecords() and Stream.toList() hold the whole dataset in memory.

To read a CSV file in Java, open the file with an explicit UTF-8 reader and hand it to Apache Commons CSV, which gives you records, quoted fields and access by header name. Use BufferedReader only for files you produce yourself that never contain quotes or multi-line fields. Everything else, including String.split(","), breaks on the first quoted comma.

Here is the shortest complete version. It prints the first name from every row of a file whose first line is the 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;

public class CsvQuickStart {
    public static void main(String[] args) throws IOException {
        CSVFormat format = CSVFormat.DEFAULT.builder()
                .setHeader()
                .setSkipHeaderRecord(true)
                .get();
        try (Reader reader = Files.newBufferedReader(Path.of("data.csv"), StandardCharsets.UTF_8);
             CSVParser parser = format.parse(reader)) {
            for (CSVRecord record : parser) {
                System.out.println(record.get("First"));
            }
        }
    }
}

Commons CSV is one dependency, org.apache.commons:commons-csv:1.14.1, the current release on Maven Central (released 2025-07-27 per the project's changes report). Every example targets JDK 25, the current long-term support release Oracle shipped on 2025-09-16.

Advertisement

Lines Are Not Records: Two Sample Files and the split() Trap

Save this as data.csv, UTF-8 encoded, in your working directory. Its first record holds the column names:

First,Last,Age
John,Doe,23
Sam,Smith,40
Jan,Miller,18

That file has one record per physical line, which is why naive code appears to work on it. A file exported from a real system looks more like complex.csv:

First,Last,Age,Note
Jane,"Doe, Jr.",31,"Said ""hello"""
Sam,Smith,40,"Two
lines"
Jan,Miller,18,

RFC 4180 defines the rules: a quoted field may contain commas and line breaks, and a double quote inside a quoted field is written as two double quotes. So Sam's record spans two physical lines, Jane's last name contains a comma, and Jan's Note is an empty field. Four records, five lines.

Why String.split Is Not a CSV Parser

line.split(",") cannot tell a delimiter from a comma inside quotes, and because it works one line at a time it has no way to know that "Two continues on the next line. There is a second, quieter trap. Oracle's String Javadoc says the one-argument split uses a limit of zero, and "trailing empty strings will be discarded". Jan's row therefore splits into three values, not four, and values[3] throws. A negative limit keeps the empty strings but still does nothing about quoting:

// Fragment: only for input guaranteed to contain no quotes or embedded line breaks.
String[] values = "Jan,Miller,18,".split(",", -1); // ["Jan", "Miller", "18", ""]

Our read: split is fine for a format you control and have documented as quote-free. For anything labeled "CSV" by someone else, it is a bug waiting for its first customer name with a comma in it.

Read a CSV File in Java Using BufferedReader

This reads text lines, not CSV fields, and it is the right tool when that is all you need: a log of fixed, quote-free rows, or a quick look at a file's raw contents. Save it as LineReader.java beside data.csv:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class LineReader {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("data.csv");

        try (BufferedReader reader =
                Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

Run it with java LineReader.java; the JDK 25 launcher compiles a single source file in memory and runs it. The output is the four lines of the file, unchanged.

Two details matter more than the loop. Files.newBufferedReader(Path, Charset) names the encoding, so the program reads the same bytes the same way on every machine. The no-charset FileReader constructor uses the platform default instead, which JEP 400 made UTF-8 from JDK 18 onward but which was Windows-1252 on older Windows JDKs. And try-with-resources closes the reader whether the loop finishes or throws.

readLine() returns physical lines. Feed it complex.csv and Sam's record comes back as two separate strings, Sam,Smith,40,"Two and lines". No amount of splitting repairs that.

Scanner Reads Lines Too, and Hides I/O Errors

Scanner can read the same lines, and its nextInt() style methods are convenient for controlled token input. Save this as ScannerLines.java:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Scanner;

public class ScannerLines {
    public static void main(String[] args) throws IOException {
        try (Scanner scanner = new Scanner(
                Path.of("data.csv"), StandardCharsets.UTF_8)) {
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            IOException failure = scanner.ioException();
            if (failure != null) {
                throw failure;
            }
        }
    }
}

The ioException() check is not optional. The Scanner Javadoc states that if the underlying read throws an IOException, "the scanner assumes that the end of the input has been reached". Without that check, a disk error looks like a short file and your import reports success. Setting a comma delimiter does not make Scanner a CSV parser either; it has the same quoting blind spot as split. For a deeper comparison of the three readers, see FileReader vs BufferedReader vs Scanner.

Which Approach Should You Choose?

ApproachWhat it gives youUse it for
BufferedReaderBuffered character and line reading, explicit charsetRaw text, or a quote-free format you control
ScannerLine reading plus token conversion; swallows read errors until you askInteractive or controlled token input, not CSV
String.splitField splitting with no quoting rules; drops trailing empties by defaultNothing labeled CSV by someone else
Apache Commons CSVRecords, quoted fields, header access, dialect presets, a printerEvery real import or export

Apache Commons CSV Example: Read by Header Name

Add the dependency to your pom.xml once; every Commons CSV example on this page uses it:

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

Run through Maven as usual, or use source-file mode with a classpath. Commons CSV 1.14.1 declares commons-io and commons-codec as compile dependencies in its POM, so the classpath needs all three jars, not just commons-csv-1.14.1.jar. The easy way is to let Maven collect them: mvn dependency:copy-dependencies puts them under target/dependency (see the plugin goal), and java -cp "target/dependency/*" CsvByHeader.java data.csv compiles and runs the file. The launcher manual lists --class-path among the options it honors when compiling a source file.

Save this as CsvByHeader.java. It discovers the header, refuses files that lack the required columns, checks every record's width, and prints each person's first name:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.DuplicateHeaderMode;

public class CsvByHeader {
    private static final CSVFormat FORMAT = CSVFormat.DEFAULT.builder()
            .setDelimiter(',')
            .setQuote('"')
            .setHeader()
            .setSkipHeaderRecord(true)
            .setDuplicateHeaderMode(DuplicateHeaderMode.DISALLOW)
            .get();

    public static void main(String[] args) {
        String file = args.length == 0 ? "data.csv" : args[0];
        try {
            read(Path.of(file));
        } catch (IOException | RuntimeException e) {
            // Commons CSV wraps read failures during iteration in an unchecked exception.
            System.err.println("CSV import failed for " + file + ": " + e.getMessage());
            System.exit(1);
        }
    }

    private static void read(Path path) throws IOException {
        try (BufferedReader reader =
                Files.newBufferedReader(path, StandardCharsets.UTF_8);
             CSVParser parser = FORMAT.parse(reader)) {
            if (!parser.getHeaderNames().containsAll(
                    List.of("First", "Last", "Age"))) {
                throw new IllegalArgumentException(
                        "Required headers: First, Last, Age");
            }

            for (CSVRecord record : parser) {
                if (!record.isConsistent()) {
                    throw new IllegalArgumentException(
                            "Wrong field count at record " + record.getRecordNumber());
                }
                System.out.println(record.get("First"));
            }
        }
    }
}

For data.csv the output is:

John
Sam
Jan

Run it against complex.csv and it prints Jane, Sam and Jan. For Jane, record.get("Last") returns Doe, Jr. and record.get("Note") returns Said "hello"; Jan's Note is the empty string. That is the whole argument for a parser in three lines of output.

What Each Builder Setting Does

  • setHeader() with no arguments tells the parser to take column names from the first record.
  • setSkipHeaderRecord(true) keeps that header row out of the data iteration.
  • setDuplicateHeaderMode(DuplicateHeaderMode.DISALLOW) rejects a file with two columns of the same name instead of silently letting the last one win on get(name). The enum also offers ALLOW_ALL (the DEFAULT format's setting) and ALLOW_EMPTY.
  • get() builds the format. The older build() is deprecated in the CSVFormat.Builder docs, as is withFirstRecordAsHeader() on CSVFormat.

CSVFormat.DEFAULT is RFC 4180 plus empty-line skipping, per the CSVFormat docs. isConsistent() only checks that a record's field count matches the header count. It does not know that Age must be a number; that is your job, and the next section does it.

Other Delimiters and Headerless Files

For semicolon-separated input, change the builder to setDelimiter(';'). Never guess the delimiter from the file extension. For a headerless three-column file, replace setHeader() with setHeader("First", "Last", "Age") and use setSkipHeaderRecord(false); with names supplied by you, skipping the first record would throw away real data.

Read a CSV File From the Classpath (resources Folder)

A path such as src/main/resources/data.csv works only when you run from the project root, and stops working once the application is packaged as a JAR. Load bundled files from the classpath instead. Class.getResourceAsStream returns null when the resource is missing, so check for that before parsing:

// Fragment: replaces Files.newBufferedReader(...) for a file under src/main/resources.
// Needs: import java.io.InputStream; import java.io.InputStreamReader;
InputStream in = CsvByHeader.class.getResourceAsStream("/data.csv");
if (in == null) {
    throw new IllegalStateException("data.csv not found on the classpath");
}
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);

Map CSV Rows to Java Records

Most imports want a List<Person>, not a list of string arrays. A Java record is the natural row type: Oracle's records guide explains that the compiler generates a private final field and a public accessor per component, a canonical constructor, and equals, hashCode and toString. Save this as CsvToRecords.java:

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class CsvToRecords {
    record Person(String first, String last, int age) {}

    private static final CSVFormat FORMAT = CSVFormat.DEFAULT.builder()
            .setHeader()
            .setSkipHeaderRecord(true)
            .setTrim(true)
            .get();

    public static void main(String[] args) throws IOException {
        Path path = Path.of(args.length == 0 ? "data.csv" : args[0]);
        try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
             CSVParser parser = FORMAT.parse(reader)) {
            List<Person> people = parser.stream()
                    .map(CsvToRecords::toPerson)
                    .toList();
            for (Person p : people) {
                System.out.println(p.first() + " is " + p.age());
            }
        }
    }

    static Person toPerson(CSVRecord record) {
        if (!record.isConsistent()) {
            throw new IllegalArgumentException("Record " + record.getRecordNumber()
                    + ": expected " + record.getParser().getHeaderNames().size()
                    + " fields, found " + record.size());
        }
        try {
            return new Person(record.get("First"), record.get("Last"),
                    Integer.parseInt(record.get("Age")));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Record " + record.getRecordNumber()
                    + ": Age is not a whole number: \"" + record.get("Age") + "\"", e);
        }
    }
}

For data.csv the output is:

John is 23
Sam is 40
Jan is 18

Three choices in that code earn their place. CSVParser.stream(), present since Commons CSV 1.9.0, lets you use map and toList() the same way you would on any collection; if the lambda syntax is new to you, our guide to lambda expressions covers method references like CsvToRecords::toPerson. setTrim(true) strips blanks around each value, because Integer.parseInt accepts only digits and an optional sign, so " 23" would throw.

The third choice is the error message. Every one carries getRecordNumber(), which is the position of the record in the file. Change Sam's age to forty and the program fails with Sam's record number followed by Age is not a whole number: "forty", which a support engineer can act on. A bare NumberFormatException: For input string: "forty" is not.

One caveat: record numbers are not line numbers. The CSVRecord docs note that with multi-line fields the two diverge, and CSVParser.getCurrentLineNumber() reports the line instead. Label your messages accordingly. If you want a plain string table rather than typed records, record.toList() returns a fresh List<String> per row; the Java Collections guide covers the trade-offs between List implementations.

Advertisement

Handle a UTF-8 BOM and Excel Exports

If your header lookup fails with a message like Mapping for First not found and the header plainly says First, the file almost certainly starts with a byte order mark. Strip it before parsing, with either of the two fragments below.

The Unicode FAQ describes it as the three bytes EF BB BF, the UTF-8 form of U+FEFF, used purely as a signature that "an otherwise unmarked text file is in UTF-8". Excel's "CSV UTF-8" save option commonly writes one, and the Commons CSV user guide singles out "some Excel CSV files" as the reason its BOM recipe exists. Java's UTF-8 decoder does not strip it, so the first column name arrives as U+FEFF followed by First, a string that prints identically to First in a terminal and matches nothing.

The Commons CSV guide's fix uses BOMInputStream from Commons IO (add commons-io:commons-io:2.22.0, the current version on Maven Central). The BOMInputStream constructors are deprecated in favor of the builder, which excludes a UTF-8 BOM by default:

// Fragment: replaces Files.newBufferedReader(...) in any example above.
// Needs: import java.io.InputStreamReader; import org.apache.commons.io.input.BOMInputStream;
Reader reader = new InputStreamReader(
        BOMInputStream.builder().setPath(path).get(),
        StandardCharsets.UTF_8);

If you would rather not add a second library for three bytes, the JDK's PushbackReader does the job: read one character, and push it back unless it is U+FEFF.

// Fragment: wrap the reader before passing it to CSVFormat.parse().
// Needs: import java.io.PushbackReader;
static Reader withoutBom(Reader in) throws IOException {
    PushbackReader reader = new PushbackReader(in);
    int first = reader.read();
    if (first != -1 && first != 0xFEFF) {
        reader.unread(first);
    }
    return reader;
}

Excel has a second habit. Its CSV delimiter follows the Windows list separator, and Microsoft's import and export guide explains that setting the decimal separator to a comma "forces Excel to use a semi-colon for the list separator". That is the default in much of Europe, so a file from a German or French colleague is usually semicolon-delimited. Use setDelimiter(';'), and consider starting from CSVFormat.EXCEL, which the CSVFormat docs describe as RFC 4180 with missing column names and trailing data allowed.

Write a CSV File in Java

The same library writes CSV, and you should let it: hand-building lines with String.join(",") reproduces every quoting bug from the split section in reverse. CSVPrinter.printRecord promises that "the values will be quoted if needed" and that quotes and newlines are escaped. Save this as CsvWriter.java:

import java.io.IOException;
import java.io.Writer;
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.CSVPrinter;

public class CsvWriter {
    private static final CSVFormat FORMAT = CSVFormat.DEFAULT.builder()
            .setHeader("First", "Last", "Note")
            .get();

    public static void main(String[] args) throws IOException {
        try (Writer writer = Files.newBufferedWriter(Path.of("out.csv"), StandardCharsets.UTF_8);
             CSVPrinter printer = FORMAT.print(writer)) {
            printer.printRecord("Jane", "Doe, Jr.", "Said \"hello\"");
            printer.printRecord("Sam", "Smith", "Two\nlines");
        }
    }
}

Because the format carries a header and does not skip it, the printer writes the header row first. The resulting out.csv is:

First,Last,Note
Jane,"Doe, Jr.","Said ""hello"""
Sam,Smith,"Two
lines"

Jane's comma and quotes and Sam's line break all come out RFC 4180 clean. DEFAULT ends records with CRLF, which Excel and most tools expect. Pass a record's components straight through with printer.printRecord(p.first(), p.last(), p.age()), or an Iterable or Stream; the printer has overloads for all three. Write with Files.newBufferedWriter and a named charset for the same reason you read with one.

Correct quoting does not make an export safe to open in a spreadsheet. If a cell value comes from users and starts with =, +, - or @, a spreadsheet can evaluate it as a formula, and CSVPrinter will not stop that. The OWASP CSV injection page warns that the often-suggested single-quote prefix is not reliable in Excel after the file is saved and re-opened, and gives a leading tab character inside the quoted field as its Excel-resistant mitigation. The tab stays in the data, so apply it only to files meant for people with spreadsheets, never to files another program will import.

Stream Large Files and Handle Import Failures

The for (CSVRecord record : parser) loop already streams: each record is parsed, processed and dropped. Two calls undo that. CSVParser.getRecords() reads everything remaining into a list, and parser.stream().toList() in the records example does the same, which is fine for a 4-row demo and wrong for a 4 GB export. For big files, keep the stream lazy: parser.stream().map(CsvToRecords::toPerson).forEach(repository::save), or batch with a counter and flush every few thousand rows.

Memory is bounded by the largest single record plus whatever you accumulate downstream, not by file size. A one-field record holding a 50 MB blob still needs 50 MB. Keep the destination incremental too: write to the database or output file as you go, in transactions sized for a sensible retry.

On failures, note what the library throws. CSVException, introduced in 1.12.0, extends IOException and signals invalid input such as broken quoting. The CSVParser docs say getRecords() throws UncheckedIOException on a parse or read failure, and that an IOException during iteration is rethrown unchecked, which is why CsvByHeader catches RuntimeException alongside IOException.

Printing the message and exiting with status 1 is a complete policy for a command-line tool. In a service it is not: preserve the cause, record which record number failed, and decide whether partial results are rolled back, staged or quarantined. Never report success for a file you imported half of.

Which Java CSV Library?

Commons CSV is our default because it is small, has no bean-mapping magic to debug, and covers every dialect we have met through its presets. The other two earn their place in specific situations.

LibraryCurrent versionCoordinatesPick it when
Apache Commons CSV1.14.1org.apache.commons:commons-csvYou want records, header access and presets (DEFAULT, EXCEL, RFC4180, TDF, POSTGRESQL_CSV) with no annotations. Map to records by hand as above.
OpenCSV5.12.0com.opencsv:opencsvYou want bean binding driven by annotations: @CsvBindByName maps a field to a header, @CsvBindByPosition to a column index.
Jackson CSV3.3.0 (tools.jackson.dataformat), 2.23.0 (com.fasterxml.jackson.dataformat)jackson-dataformat-csvJackson is already on your classpath. CsvMapper and CsvSchema bind rows to the same POJOs your JSON uses; see our ObjectMapper guide for the shared data-binding model.
String.splitJDKnoneA quote-free format you control, documented as such. Use split(",", -1) to keep trailing empty fields.

Two version notes. Jackson 3.0 shipped on 2025-10-03 and moved its Maven groups and packages from com.fasterxml.jackson to tools.jackson, per the project's release page; the 3.x CSV module is tools.jackson.dataformat:jackson-dataformat-csv and the 2.x line continues at com.fasterxml.jackson.dataformat. OpenCSV's 5.12.0 dates from 2025-07-26 per its project page. All three are maintained; none of this is a reason to switch a working importer.

Common Mistakes

  • Trusting the default charset. Name the producer's encoding. UTF-8 cannot repair a file written as Windows-1252, and the fix is Charset.forName("windows-1252") at the reader, not replace calls later.
  • Skipping bad rows silently. Decide which failures are recoverable. A wrong field count is a quarantine; broken quoting means the parser can no longer find record boundaries, so stop.
  • Writing CSV with string concatenation. One customer named O'Brien, Jr. and your export no longer round-trips. Use CSVPrinter.

Before shipping an importer, test these inputs: quoted commas, doubled quotes, multi-line fields, trailing empty values, a BOM, a semicolon file, non-ASCII names, a missing required header, duplicate headers, an inconsistent field count, and a 1 GB file. Each one maps to a line in this article.

How This Comes Up in Interviews

"Parse this CSV" makes a good Java interview warm-up because it tests judgment, not syntax. The weak answer is split(","). The strong answer names the three things that break it (quoted delimiters, doubled quotes, multi-line fields), reaches for a library, and talks about streaming, charsets and error messages that include a record number. Follow-ups usually go to memory ("how would you handle a 10 GB file?"), to failure policy ("a row in the middle is malformed; what happens to the rest?") and to Java fundamentals such as try-with-resources, checked versus unchecked exceptions and why a record beats a mutable class for a row type.

A natural data-structure follow-up is a map: "load this file and look people up by last name", which turns into a conversation about HashMap sizing and collisions. Our Java HashMap interview questions cover that ground, and the interview hub collects the rest of the Java and system-design sets.

FAQ

How do I read a CSV file in Java with a header row?

Use Apache Commons CSV with setHeader() and setSkipHeaderRecord(true). The parser takes column names from the first record, skips it during iteration, and lets you read values with record.get("First") instead of a column index.

Can I parse CSV in Java with String.split?

Only for a format you control that forbids quotes and embedded line breaks. split(",", -1) keeps trailing empty fields, but no form of split handles a quoted comma, a doubled quote or a field that spans two lines.

How do I read a CSV file into a list of Java objects?

Declare a record such as Person(String first, String last, int age), convert each CSVRecord with record.get(name) and Integer.parseInt, and collect with parser.stream().map(...).toList(). Include record.getRecordNumber() in every conversion error so a bad row can be found.

How do I read a large CSV file in Java without loading it all into memory?

Iterate the CSVParser or use parser.stream() with forEach, and process or batch each record as it arrives. Avoid getRecords() and toList(), which hold every record; memory then depends on the largest record and on what you accumulate downstream.

Why does my CSV header not match when the first column name looks right?

The file probably starts with a UTF-8 byte order mark, which Excel's CSV UTF-8 export commonly writes. Java decodes it as U+FEFF in front of the first header. Wrap the input in Commons IO's BOMInputStream or a PushbackReader that discards a leading U+FEFF.

How do I write a CSV file in Java?

Open a writer with Files.newBufferedWriter(path, StandardCharsets.UTF_8), create a CSVPrinter from a CSVFormat with setHeader(...), and call printRecord for each row. The printer quotes values containing commas, quotes or line breaks and doubles embedded quotes, so the file reads back correctly.

Further Reading

Advertisement

Corrections

No corrections to date Report an error

Advertisement