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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Defining one CSVFormat with named headers keeps read and write logic consistent and column-order safe.
- 2Try-with-resources guarantees readers, writers, and parsers close even when parsing throws.
- 3Using BigDecimal with toPlainString avoids floating-point and scientific-notation surprises for money.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/reading-and-writing-csv-with-commons-csv-explained-java-39d4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.