Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read a CSV file

Short answer

Suppose there is a file users.csv:

name,age,city
Anna,30,Berlin
Oleg,25,Paris
Maria,41,Rome

Skip the header line and split each line by comma:

void main() throws IOException {
    try (var lines = Files.lines(Path.of("users.csv"))) {
        lines.skip(1).forEach(line -> {
            String[] cells = line.split(",");
            IO.println(cells[0] + " lives in " + cells[2]);
        });
    }
}

Output:

Anna lives in Berlin
Oleg lives in Paris
Maria lives in Rome

Into objects

Turn each line into a record — it is easier to work with afterwards:

record User(String name, int age, String city) {
    static User fromCsv(String line) {
        String[] cells = line.split(",");
        return new User(cells[0].strip(), Integer.parseInt(cells[1].strip()), cells[2].strip());
    }
}
 
void main() throws IOException {
    List<User> users;
    try (var lines = Files.lines(Path.of("users.csv"))) {
        users = lines.skip(1).filter(line -> !line.isBlank()).map(User::fromCsv).toList();
    }
    IO.println(users.stream().mapToInt(User::age).average().orElse(0));
}

Output:

32.0

Another separator

Spreadsheets from Excel in European locales are often separated by semicolons. The second argument -1 keeps empty cells at the end of a line:

void main() {
    String line = "Anna;30;;";
 
    IO.println(line.split(";").length);
    IO.println(line.split(";", -1).length);
}

Output:

2
4

Common mistake

Splitting by comma a file where values contain commas inside quotes. The line "Smith, John",42 falls apart into three parts instead of two:

void main() {
    String line = "\"Smith, John\",42";
    IO.println(line.split(",").length);
}

Output:

3

For real CSV with quotes and line breaks inside values, use a library — for example, Apache Commons CSV or OpenCSV.

Functions used in this recipe

  • Files.lines() — Reads a file lazily as a stream of lines, without loading it into memory.
  • String.split() — Splits a string into an array of parts by a separator.
  • Integer.parseInt() — Converts a string containing an integer to an int.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().

Thanks for reading!

Donate to the site — we work hard for you.