00:00

How to Read a CSV File in Java: 4 Ways with Examples

Last updated:

CSV (comma-separated values) is the most common format for exchanging tabular data: bank statements, product catalogues and spreadsheet exports all use it. Reading a simple CSV file in Java takes only a few lines, but real-world files with quoted fields need more care.

This tutorial shows every common way to read a CSV file in Java 25, from a quick split to a quote-aware parser.

1. What Is a CSV File?

A CSV file is a text file in which each line is a record and fields are separated by commas. The first line is often a header with column names. A field that contains a comma is wrapped in double quotes, and a double quote inside such a field is written twice (""). The format is described in RFC 4180.

Sample CSV
name,address,note
Kiran,"12 MG Road, Bengaluru",regular

2. Ways to Read a CSV File at a Glance

WayHandles quoted commas?Best for
BufferedReader + split(",")NoSimple files you control
Files.lines() + recordsNoTurning rows into typed objects
Scanner with a delimiterNoReading numbers directly
Custom quote-aware parserYesReal-world files without extra libraries
A CSV libraryYesProduction code

3. Using BufferedReader and split()

For simple files without quoted commas, read each line and split it.

CsvWithBufferedReader.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CsvWithBufferedReader {
    public static void main(String[] args) throws IOException {
        Path csv = Files.createTempFile("students", ".csv");
        Files.writeString(csv, "roll,name,marks\n1,Asha,88\n2,Rohit,74\n3,Meera,91\n");

        try (BufferedReader in = Files.newBufferedReader(csv)) {
            String header = in.readLine();                         // skip the header row
            System.out.println("Columns: " + header);
            String line;
            while ((line = in.readLine()) != null) {
                String[] cols = line.split(",");
                System.out.println(cols[1] + " scored " + cols[2]);
            }
        }
        Files.delete(csv);
    }
}
Output
Columns: roll,name,marks
Asha scored 88
Rohit scored 74
Meera scored 91

How it works

  1. The first readLine() consumes the header row.
  2. split(",") turns each line into an array of fields.

4. Mapping Rows to Records with Files.lines()

Records (Java 16) give each row a type, so the rest of the program works with real objects instead of string arrays.

CsvToRecords.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class CsvToRecords {

    record Product(String sku, String name, double price, int stock) {
        static Product fromCsv(String line) {
            String[] c = line.split(",");
            return new Product(c[0].strip(), c[1].strip(), Double.parseDouble(c[2]), Integer.parseInt(c[3].strip()));
        }
    }

    public static void main(String[] args) throws IOException {
        Path csv = Files.createTempFile("inventory", ".csv");
        Files.writeString(csv, """
                sku,name,price,stock
                P1,Desk lamp,1299.00,12
                P2,Office chair,6499.00,0
                P3,Monitor stand,899.50,40
                """);

        List<Product> products;
        try (Stream<String> lines = Files.lines(csv)) {
            products = lines.skip(1).map(Product::fromCsv).toList();     // each row becomes a record
        }
        System.out.println("Out of stock: " + products.stream().filter(p -> p.stock() == 0).map(Product::name).toList());
        System.out.println("Cheapest: " + products.stream().min(Comparator.comparingDouble(Product::price)).orElseThrow());
        Files.delete(csv);
    }
}
Output
Out of stock: [Office chair]
Cheapest: Product[sku=P3, name=Monitor stand, price=899.5, stock=40]

How it works

  1. A text block (Java 15) holds the sample data.
  2. Product.fromCsv() converts one line into a record, parsing numbers and removing spaces with strip().
  3. skip(1) drops the header, and toList() (Java 16) collects the records.

5. Using Scanner with a Delimiter

A Scanner can treat both commas and line breaks as delimiters and read numbers directly.

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

public class CsvWithScanner {
    public static void main(String[] args) throws IOException {
        Path csv = Files.createTempFile("trips", ".csv");
        Files.writeString(csv, "Delhi,Agra,233\nMumbai,Pune,148\nChennai,Vellore,140\n");

        int totalKm = 0;
        try (Scanner in = new Scanner(csv, StandardCharsets.UTF_8)) {
            in.useDelimiter("[,\\n]");                         // split on commas and new lines
            while (in.hasNext()) {
                String from = in.next();
                String to = in.next();
                int km = in.nextInt();                         // parsed straight to int
                totalKm += km;
                System.out.println(from + " -> " + to + ": " + km + " km");
            }
        }
        System.out.println("Total: " + totalKm + " km");
        Files.delete(csv);
    }
}
Output
Delhi -> Agra: 233 km
Mumbai -> Pune: 148 km
Chennai -> Vellore: 140 km
Total: 521 km

How it works

  1. useDelimiter("[,\\n]") splits on commas and new lines.
  2. nextInt() converts the distance without Integer.parseInt().

6. Handling Quoted Fields

Real files contain addresses and notes with commas and quotes. A small parser that tracks whether it is inside quotes handles them.

CsvWithQuotes.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class CsvWithQuotes {

    // Splits one CSV line, honouring "quoted, fields" and "" escapes
    static List<String> parse(String line) {
        List<String> fields = new ArrayList<>();
        StringBuilder field = new StringBuilder();
        boolean inQuotes = false;
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            if (inQuotes) {
                if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; }
                else if (c == '"') inQuotes = false;
                else field.append(c);
            } else if (c == '"') {
                inQuotes = true;
            } else if (c == ',') {
                fields.add(field.toString());
                field.setLength(0);
            } else {
                field.append(c);
            }
        }
        fields.add(field.toString());
        return fields;
    }

    public static void main(String[] args) throws IOException {
        Path csv = Files.createTempFile("addresses", ".csv");
        Files.writeString(csv, """
                name,address,note
                Kiran,"12 MG Road, Bengaluru",regular
                Sana,"5 Park Street, Kolkata","asked for \"\"gift wrap\"\""
                """);

        for (String line : Files.readAllLines(csv).subList(1, 3)) {
            List<String> f = parse(line);
            System.out.println(f.size() + " fields -> " + f);
        }
        System.out.println("Naive split gives " + "Kiran,\"12 MG Road, Bengaluru\",regular".split(",").length + " fields");
        Files.delete(csv);
    }
}
Output
3 fields -> [Kiran, 12 MG Road, Bengaluru, regular]
3 fields -> [Sana, 5 Park Street, Kolkata, asked for "gift wrap"]
Naive split gives 4 fields

How it works

  1. Inside quotes, commas are kept as text; a doubled quote becomes one quote character.
  2. Both rows have exactly 3 fields, while a naive split(",") wrongly finds 4 in the first row.
  3. This parser handles one line at a time; fields with line breaks inside quotes need a full library.

7. Using a CSV Library

For production systems, a well-tested library such as Apache Commons CSV or OpenCSV handles quotes, line breaks inside fields, different separators, headers and character encodings. These are third-party dependencies added through Maven or Gradle; they are not part of the JDK, so check their documentation for current versions.

8. Common Mistakes and Best Practices

  • Using split(",") on files with quoted fields. Commas inside quotes break the columns.
  • Forgetting the header row. Parsing it as data causes NumberFormatException.
  • Ignoring the encoding. Spreadsheet exports are not always UTF-8; pass the right charset.
  • Assuming every row is complete. Check the number of fields before using them.
  • Loading huge files into memory. Process rows one at a time with BufferedReader or Files.lines().

9. Summary

  • Each CSV line is a record; fields are separated by commas.
  • BufferedReader with split() works for simple files.
  • Map rows to records for type-safe processing.
  • Quoted fields need a quote-aware parser or a CSV library.
  • Skip the header and validate each row.

Related Tutorials

10. Official Java Documentation References