Skip to lesson

Turn a CSV line into a record

A CSV file is a plain text table: one row per line, with the values in a row separated by commas. Turning one such line into a typed Java object is the first step of almost every import program: marks lists, fee payments, train bookings and bank statements.

What a CSV file is

CSV (comma-separated values) is a plain text format where each line is a row and commas separate the fields, often with a header line naming the columns.

CSV stands for comma-separated values. Each line is one row, each value between commas is one field, and the first line is usually a header that names the columns.

Example 1 · A CSV table is just lines of text

CsvTextDemo.javaJava
public class CsvTextDemo {    public static void main(String[] args) {        String csv = """                roll,name,marks                101,Asha Rao,87                102,Bhavesh Patel,64                103,Chitra Iyer,92                """;
        String[] lines = csv.split("\n");        System.out.println("Lines: " + lines.length);        for (int i = 0; i < lines.length; i++) {            String[] fields = lines[i].split(",");            System.out.println("line " + (i + 1) + ": " + fields.length + " fields -> " + lines[i]);        }        System.out.println("Header: " + lines[0]);        System.out.println("Data rows: " + (lines.length - 1));    }}
Output
Lines: 4
line 1: 3 fields -> roll,name,marks
line 2: 3 fields -> 101,Asha Rao,87
line 3: 3 fields -> 102,Bhavesh Patel,64
line 4: 3 fields -> 103,Chitra Iyer,92
Header: roll,name,marks
Data rows: 3

What this code does

  • The text block holds what a file marks.csv would contain. There is no hidden structure: four lines, each with two commas.
  • Every line splits into 3 fields, and the first line is the header, so there are 3 data rows. The next lesson reads the same text from a real file.

Excel, Google Sheets and almost every database can save a table as CSV, and any program can read it, because it is just text. That is why colleges, banks and booking sites use it to share data. To Java, a CSV file is only lines of String. Java does not know that 87 is a number or that 15-07-2024 is a date. Your code has to split each line and convert every field to the right type.

CSV has no single strict standard. Most files follow the common rules described in RFC 4180, which the Quoted fields lesson covers.

split, trim and parse numbers

line.split(",") cuts a line at every comma and returns the pieces as a String[]. Each piece is still text, so a number field must go through Integer.parseInt or Double.parseDouble.

Example 2 · split, trim and parseInt

SplitTrimParseDemo.javaJava
public class SplitTrimParseDemo {    public static void main(String[] args) {        String line = "101, Asha Rao , 87";        String[] parts = line.split(",");
        System.out.println("Fields: " + parts.length);        for (String p : parts) {            System.out.println("[" + p + "]");        }
        int roll = Integer.parseInt(parts[0].trim());        String name = parts[1].trim();        int marks = Integer.parseInt(parts[2].trim());        System.out.println(name + " (roll " + roll + ") scored " + marks);
        try {            Integer.parseInt(parts[2]);        } catch (NumberFormatException e) {            System.out.println("Without trim: " + e.getMessage());        }    }}
Output
Fields: 3
[101]
[ Asha Rao ]
[ 87]
Asha Rao (roll 101) scored 87
Without trim: For input string: " 87"

What this code does

  • The square brackets show the spaces kept inside each field: [ Asha Rao ] and [ 87]. split cuts only at the commas; it never removes spaces.
  • trim() removes the spaces, so parseInt gets 87. Without it, parseInt(" 87") fails with the message For input string: " 87".

Example 3 · Trap: empty fields at the end disappear

SplitLimitDemo.javaJava
import java.util.Arrays;
public class SplitLimitDemo {    public static void main(String[] args) {        String line = "102,Bhavesh,,";   // marks and grade are empty
        String[] a = line.split(",");        String[] b = line.split(",", -1);        System.out.println("split(\",\")     -> " + a.length + " " + Arrays.toString(a));        System.out.println("split(\",\", -1) -> " + b.length + " " + Arrays.toString(b));
        try {            String grade = a[3];            System.out.println("grade = " + grade);        } catch (ArrayIndexOutOfBoundsException e) {            System.out.println("a[3] fails: " + e.getMessage());        }        System.out.println("b[2] is empty: " + b[2].isEmpty());        System.out.println("b[3] is empty: " + b[3].isEmpty());    }}
Output
split(",")     -> 2 [102, Bhavesh]
split(",", -1) -> 4 [102, Bhavesh, , ]
a[3] fails: Index 3 out of bounds for length 2
b[2] is empty: true
b[3] is empty: true

What this code does

  • The row has 4 fields, two of them empty. Plain split(",") removes trailing empty strings, so a has only 2 items and a[3] throws ArrayIndexOutOfBoundsException.
  • split(",", -1) keeps every field, so b has 4 items and the empty ones are "". Your code can now notice the missing value and report it instead of crashing.

Real files have spaces around commas, like 101, Asha, 87. parseInt(" 87") throws NumberFormatException, because a space is not a digit. Call trim() on every field before you use it. One more trap: plain split(",") drops empty fields at the end of the line. "102,Bhavesh,,".split(",") gives only 2 pieces. split(",", -1) keeps them, so a row always has as many fields as it has commas plus one.

Fix the error

Fix the CSV crashes

Read the error from the program, then pick the line that fixes it.

Round 1 of 2

A row with a space after the comma.

String line = "101, Asha, 87";
String[] f = line.split(",");
int marks = Integer.parseInt(f[2]);
System.out.println(marks);

Error

Exception in thread "main" java.lang.NumberFormatException: For input string: " 87"

A record class for each row

A record is a short class for plain data: record Student(int roll, String name, int marks) {} gives you a constructor, getters, equals, hashCode and toString in one line. One record per row type keeps the rest of the program clean.

Example 4 · A Student record with a fromCsv factory

StudentRecordDemo.javaJava
import java.util.List;
record Student(int roll, String name, int marks) {    static Student fromCsv(String line) {        String[] f = line.split(",", -1);        if (f.length != 3) {            throw new IllegalArgumentException("Expected 3 fields but got " + f.length + ": " + line);        }        int roll = Integer.parseInt(f[0].trim());        String name = f[1].trim();        int marks = Integer.parseInt(f[2].trim());        return new Student(roll, name, marks);    }
    boolean passed() {        return marks >= 35;    }}
public class StudentRecordDemo {    public static void main(String[] args) {        List<String> lines = List.of("101,Asha Rao,87", "102, Bhavesh Patel ,31", "103,Chitra Iyer,92");        for (String line : lines) {            Student s = Student.fromCsv(line);            System.out.println(s + " passed=" + s.passed());        }
        try {            Student.fromCsv("104,Dev Sharma");        } catch (IllegalArgumentException e) {            System.out.println("Bad row: " + e.getMessage());        }    }}
Output
Student[roll=101, name=Asha Rao, marks=87] passed=true
Student[roll=102, name=Bhavesh Patel, marks=31] passed=false
Student[roll=103, name=Chitra Iyer, marks=92] passed=true
Bad row: Expected 3 fields but got 2: 104,Dev Sharma

What this code does

  • All the split, trim and parse work sits in fromCsv. The loop in main deals only with Student objects, which have real int fields and methods like passed().
  • The field-count check turns a short row into a clear message that shows the line itself, instead of a puzzling ArrayIndexOutOfBoundsException later.

Put the parsing in a static factory method on the record, such as Student.fromCsv(line). A static factory method is a static method that builds and returns an object. All the split, trim and parse code then lives in one place. The factory method should also check the row. If the number of fields is wrong, throw IllegalArgumentException with the line in the message. A clear message now saves an hour of debugging later.

Converting dates and decimal values

LocalDate.parse(text, formatter) turns a date field into a LocalDate. ISO dates such as 2024-07-15 need no formatter. Indian-style dates such as 15-07-2024 need DateTimeFormatter.ofPattern("dd-MM-uuuu").

Example 5 · Fee payments with a strict date format

FeePaymentDemo.javaJava
import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException;import java.time.format.ResolverStyle;
record FeePayment(String txnId, LocalDate paidOn, int amount, String purpose) {    static final DateTimeFormatter DATE =            DateTimeFormatter.ofPattern("dd-MM-uuuu").withResolverStyle(ResolverStyle.STRICT);
    static FeePayment fromCsv(String line) {        String[] f = line.split(",", -1);        if (f.length != 4) {            throw new IllegalArgumentException("Expected 4 fields but got " + f.length);        }        return new FeePayment(f[0].trim(),                LocalDate.parse(f[1].trim(), DATE),                Integer.parseInt(f[2].trim()),                f[3].trim());    }}
public class FeePaymentDemo {    public static void main(String[] args) {        FeePayment p = FeePayment.fromCsv("UPI24071501, 15-07-2024, 12500, Hostel fee");        System.out.println(p);        System.out.println("Paid on a " + p.paidOn().getDayOfWeek());        System.out.println("Late? " + p.paidOn().isAfter(LocalDate.of(2024, 7, 10)));
        DateTimeFormatter smart = DateTimeFormatter.ofPattern("dd-MM-yyyy");        System.out.println("Smart mode: " + LocalDate.parse("31-02-2024", smart));        try {            FeePayment.fromCsv("UPI24022901, 31-02-2024, 9000, Exam fee");        } catch (DateTimeParseException e) {            System.out.println("Strict mode: " + e.getMessage());        }    }}
Output
FeePayment[txnId=UPI24071501, paidOn=2024-07-15, amount=12500, purpose=Hostel fee]
Paid on a MONDAY
Late? true
Smart mode: 2024-02-29
Strict mode: Text '31-02-2024' could not be parsed: Invalid date 'FEBRUARY 31'

What this code does

  • The date field becomes a real LocalDate, so you can ask for the day of the week or compare it with the due date. The amount is whole rupees in an int, so there is no rounding problem.
  • The plain dd-MM-yyyy formatter quietly turns 31 February into 29 February. The strict formatter (with uuuu for the year) throws DateTimeParseException with a clear reason.

Add .withResolverStyle(ResolverStyle.STRICT) so that an impossible date like 31-02-2024 is rejected. Without it, the default smart mode quietly changes it to 2024-02-29, and the wrong date goes into your data. For money, keep whole rupees in an int or long, or use BigDecimal for paise. A double cannot store most decimal fractions exactly, so 0.1 + 0.2 is not exactly 0.3.

Skipping the header row

The header row holds column names such as roll,name,marks. If you send it to Student.fromCsv, parseInt("roll") throws. So the header must be skipped before parsing.

Example 6 · Check the header, then parse the rest

HeaderDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Ticket(String pnr, String name, int seat) {    static Ticket fromCsv(String line) {        String[] f = line.split(",", -1);        return new Ticket(f[0].trim(), f[1].trim(), Integer.parseInt(f[2].trim()));    }}
public class HeaderDemo {    static final String EXPECTED_HEADER = "pnr,name,seat";
    static List<Ticket> parse(List<String> lines) {        if (lines.isEmpty() || !lines.get(0).trim().equals(EXPECTED_HEADER)) {            throw new IllegalArgumentException("Wrong header, expected: " + EXPECTED_HEADER);        }        List<Ticket> tickets = new ArrayList<>();        for (int i = 1; i < lines.size(); i++) {      // start at 1: skip the header            tickets.add(Ticket.fromCsv(lines.get(i)));        }        return tickets;    }
    public static void main(String[] args) {        List<String> file = List.of("pnr,name,seat", "4521876301,Farhan,23", "4521876302,Geeta,24");        for (Ticket t : parse(file)) {            System.out.println(t.name() + " has seat " + t.seat() + " (PNR " + t.pnr() + ")");        }
        List<String> wrongFile = List.of("name,pnr,seat", "Farhan,4521876301,23");        try {            parse(wrongFile);        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }    }}
Output
Farhan has seat 23 (PNR 4521876301)
Geeta has seat 24 (PNR 4521876302)
Wrong header, expected: pnr,name,seat

What this code does

  • The loop starts at index 1, so the header line never reaches Ticket.fromCsv. Before that, the method compares the header with the expected one.
  • The second file has the columns swapped. Without the check, parseInt("23") would still work and Farhan's name would be stored as the PNR, with no error at all. The header check stops it at once.

The simplest way is to start the loop at index 1, or call skip(1) on a stream. A safer way also checks the header: if it is not exactly what you expect, the file has the wrong format, and it is better to stop at once with a clear message. Some files have the columns in a different order. Reading the header into a map from column name to index lets you find each field by name, so the order no longer matters.

Next step

Check your understanding

11 quick questions