Lesson 4 of 8
CSV Reading & Writing
CSV (Comma-Separated Values) is the most common data exchange format for flat data. Java can read and write CSV with BufferedReader and String.split() or String.join(). For complex CSV (quoted fields, embedded commas, headers), use OpenCSV or Apache Commons CSV.
CSV Operations
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class CsvOperations {
public record BookCSV(String isbn, String title, String author, double price) {}
// Write CSV
public static void exportCatalog(List<BookCSV> books, Path file) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
// Write header
writer.write("isbn,title,author,price");
writer.newLine();
// Write data rows
for (BookCSV book : books) {
// Escape commas in fields with double quotes
String line = String.join(",",
book.isbn(),
quoteIfNeeded(book.title()),
quoteIfNeeded(book.author()),
String.format("%.2f", book.price())
);
writer.write(line);
writer.newLine();
}
}
}
// Read CSV
public static List<BookCSV> importCatalog(Path file) throws IOException {
List<BookCSV> books = new ArrayList<>();
try (BufferedReader reader = Files.newBufferedReader(file)) {
String header = reader.readLine(); // skip/validate header
if (header == null || !header.startsWith("isbn"))
throw new IllegalArgumentException("Invalid CSV format");
String line;
int lineNum = 1;
while ((line = reader.readLine()) != null) {
lineNum++;
if (line.isBlank()) continue;
try {
books.add(parseLine(line));
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.err.printf("Skipping malformed line %d: %s%n", lineNum, line);
}
}
}
return books;
}
static BookCSV parseLine(String line) {
// Simple split - does NOT handle quoted commas
String[] parts = line.split(",", 4); // 4 = max splits
return new BookCSV(
parts[0].trim(),
parts[1].trim().replace(""", ""), // remove outer quotes
parts[2].trim().replace(""", ""),
Double.parseDouble(parts[3].trim())
);
}
static String quoteIfNeeded(String field) {
return field.contains(",") ? """ + field + """ : field;
}
}Quick Quiz
Tip
Tip
Practice CSV Reading Writing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for CSV Reading & Writing
Practice Task
Note
Practice Task - (1) Write a working example of CSV Reading Writing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with CSV Reading Writing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?