Java Programs›File Handling›Read a CSV File

Read a CSV File in Java

beginner·  File Handling  ·  File I/O

Problem

A CSV (comma-separated values) file stores a table as text: one row per line, with commas between the columns and often a header row first.

Read a CSV of sales by region, print each region's units, and compute the total units and revenue.

Input
region,units,price / North,12,250 / South,8,300 / East,15,200
Output
Total units: 35, revenue: 8400

Java Program

Java
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class ReadCsvFile { public static void main(String[] args) throws IOException { Path csv = Paths.get("sales.csv"); Files.writeString(csv, "region,units,price\nNorth,12,250\nSouth,8,300\nEast,15,200\n"); int totalUnits = 0; long revenue = 0; try (BufferedReader reader = Files.newBufferedReader(csv)) { String header = reader.readLine(); // skip the column names String line; while ((line = reader.readLine()) != null) { String[] cols = line.split(","); int units = Integer.parseInt(cols[1].trim()); int price = Integer.parseInt(cols[2].trim()); totalUnits += units; revenue += (long) units * price; System.out.println(cols[0] + ": " + units + " units"); } System.out.println("Columns: " + header); } System.out.println("Total units: " + totalUnits + ", revenue: " + revenue); Files.delete(csv); } }

Output

North: 12 units South: 8 units East: 15 units Columns: region,units,price Total units: 35, revenue: 8400

Core Logic

Each line is one record: skip the header, split the rest on commas, convert the numeric columns, and accumulate totals.

How It Works
  1. 1The program writes a sample sales.csv first, so it can run anywhere.
  2. 2The first readLine() reads and keeps the header row.
  3. 3Each later line is split with split(","), and columns 1 and 2 are parsed as numbers.
  4. 4Units are added to a total, and units × price is added to the revenue.
North contributes 12 × 250 = 3000, South 8 × 300 = 2400 and East 15 × 200 = 3000, giving 8400.
💡

Key Point: A plain split(",") breaks on commas inside quoted fields such as "Delhi, NCR"; real-world CSV needs a proper parser.

Complexity
Time Complexity: O(n)Space Complexity: O(L)

Why: Each of the n lines is read and parsed once, holding only the current line of length L.

Key Concepts

Files.newBufferedReader()split(",")Integer.parseInt()header row

Approach 2: Using Files.lines()

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class ReadCsvFileStream { public static void main(String[] args) throws IOException { Path csv = Paths.get("sales.csv"); Files.writeString(csv, "region,units,price\nNorth,12,250\nSouth,8,300\nEast,15,200\n"); try (Stream<String> lines = Files.lines(csv)) { long revenue = lines.skip(1) // drop the header row .map(line -> line.split(",")) .mapToLong(c -> Long.parseLong(c[1]) * Long.parseLong(c[2])) .sum(); System.out.println("Revenue: " + revenue); } Files.delete(csv); } }

Output

Revenue: 8400

Core Logic

A stream over the file's lines can skip the header and compute the revenue in one pipeline.

How It Works
  1. 1Files.lines(csv) streams the lines lazily inside try-with-resources.
  2. 2skip(1) drops the header row.
  3. 3Each row is split and mapped to units × price, and sum() adds them up.
The pipeline produces the same revenue of 8400.
💡

Key Point: The stream holds the file open until it's closed, so always use it inside try-with-resources.

Complexity
Time Complexity: O(n)Space Complexity: O(L)

Why: Lines are read lazily, one at a time.

Key Concepts

Files.lines()skip(1)mapToLong()

Interview Questions

How do you handle quoted fields that contain commas?

Use a CSV library such as OpenCSV or Apache Commons CSV, or a regex that splits only on commas outside quotes — a simple split(",") can't do it.

What if a numeric column is empty or invalid?

Integer.parseInt throws NumberFormatException. Validate or catch it per row, so one bad line doesn't stop the whole import.

Learn the Concept

Related Programs