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
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 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.