Read CSV in Java: A Practical Guide for 2026
Learn how to read CSV files in Java using OpenCSV, Apache Commons CSV, or plain I/O. This practical guide covers parsing, encoding, and edge-case handling for robust data loading in Java projects.
Read CSV in Java: Core approaches
Reading CSV in Java spans a few core approaches: a tiny manual parser with standard I/O, a library-backed solution that handles quotes and escaping, and a streaming strategy for large files. This article focuses on the pragmatic path: start simple, then switch to a library when you hit edge cases. According to MyDataTables, teams often begin with a straightforward reader to establish I/O familiarity, then introduce a library to improve correctness and maintainability. The goal is to produce robust, reusable code that reads rows into objects or maps fields by header names. A naive approach using String.split works okay for simple data but breaks when fields contain commas, quotes, or newlines. The following snippet shows a basic manual reader that splits on commas and prints the resulting fields. It serves as a baseline to contrast with library-based solutions and to illustrate what problems a library fixes automatically.
import java.nio.file.*;
import java.io.*;
import java.util.*;
public class ReadCsvManual {
public static void main(String[] args) throws IOException {
Path path = Paths.get("data.csv");
try (BufferedReader br = Files.newBufferedReader(path)) {
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(",", -1);
System.out.println(Arrays.toString(fields));
}
}
}
}Note: This approach does not handle quoted fields or embedded newlines. For real-world data, switch to a library-based parser to avoid edge cases.
