java 57 lines · 7 steps

Reading and writing CSV with Commons CSV

A repository that maps a Product list to and from a CSV file using a single shared format definition.

Explained by highlit
1package com.example.inventory;
2 
3import org.apache.commons.csv.CSVFormat;
4import org.apache.commons.csv.CSVParser;
5import org.apache.commons.csv.CSVPrinter;
6import org.apache.commons.csv.CSVRecord;
7 
8import java.io.IOException;
9import java.io.Reader;
10import java.io.Writer;
11import java.math.BigDecimal;
12import java.nio.charset.StandardCharsets;
13import java.nio.file.Files;
14import java.nio.file.Path;
15import java.util.ArrayList;
16import java.util.List;
17 
18public class ProductCsvRepository {
19 
20 private static final CSVFormat FORMAT = CSVFormat.DEFAULT.builder()
21 .setHeader("sku", "name", "price", "description")
22 .setSkipHeaderRecord(true)
23 .setIgnoreSurroundingSpaces(true)
24 .setTrim(true)
25 .build();
26 
27 public List<Product> load(Path source) throws IOException {
28 List<Product> products = new ArrayList<>();
29 try (Reader reader = Files.newBufferedReader(source, StandardCharsets.UTF_8);
30 CSVParser parser = FORMAT.parse(reader)) {
31 for (CSVRecord record : parser) {
32 products.add(new Product(
33 record.get("sku"),
34 record.get("name"),
35 new BigDecimal(record.get("price")),
36 record.get("description")
37 ));
38 }
39 }
40 return products;
41 }
42 
43 public void save(Path target, List<Product> products) throws IOException {
44 try (Writer writer = Files.newBufferedWriter(target, StandardCharsets.UTF_8);
45 CSVPrinter printer = new CSVPrinter(writer, FORMAT.builder().setSkipHeaderRecord(false).build())) {
46 for (Product product : products) {
47 printer.printRecord(
48 product.sku(),
49 product.name(),
50 product.price().toPlainString(),
51 product.description()
52 );
53 }
54 printer.flush();
55 }
56 }
57}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Defining one CSVFormat with named headers keeps read and write logic consistent and column-order safe.
  2. 2Try-with-resources guarantees readers, writers, and parsers close even when parsing throws.
  3. 3Using BigDecimal with toPlainString avoids floating-point and scientific-notation surprises for money.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Reading and writing CSV with Commons CSV — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code