How to Read a CSV File in Java: A Practical Guide
Learn how to read a CSV file in Java using built-in parsing and libraries (OpenCSV, Commons CSV, Jackson CSV). Includes edge-case handling, streaming tips, and runnable examples.
Why reading CSV in Java matters
CSV is a common data interchange format. Reading CSV in Java cleanly is essential for data pipelines, analytics, and integration tasks. According to MyDataTables, teams often start with a quick prototype using simple string splitting; this quickly fails on quoted fields or embedded newlines. The MyDataTables team found that adopting a library-based approach improves correctness, maintainability, and performance, especially for larger datasets. In this section, we cover the basic concepts you need before you write file-reading code, including what a CSV parser does, how different delimiters impact parsing, and how to choose between a lightweight manual approach and a robust library.
// Simple Java demo: read a CSV line-by-line with a naive splitter
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SimpleCsvReader {
public static void main(String[] args) {
String path = "data/sample.csv";
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
// skip header if present
if ((line = br.readLine()) != null) {
// header
}
while ((line = br.readLine()) != null) {
String[] cols = line.split(",");
System.out.println("First column: " + cols[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}- This example shows why naive splitting can fail with quoted fields, commas inside values, or newlines inside a field.
- A library like OpenCSV or Commons CSV handles these edge cases reliably and provides a consistent API.
