Real World Example

Daily Sales Report from a CSV Export

Retail and e-commerce teams often receive a daily CSV export (orders from a store or marketplace). A small Java job reads it, skips bad rows, totals sales by city and writes a summary report file for the business team.

Example

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("sales");
        Path input = dir.resolve("orders-2024-08-15.csv");
        Path report = dir.resolve("report-2024-08-15.txt");
        try {
            Files.write(input, List.of(
                    "orderId,city,amount",
                    "O1,Bengaluru,1499",
                    "O2,Chennai,899",
                    "O3,Bengaluru,2499",
                    "O4,Hyderabad,abc",
                    "O5,Chennai,1200",
                    "O6,Hyderabad,650"));

            Map<String, Integer> byCity = new TreeMap<>();
            int skipped = 0;
            List<String> lines = Files.readAllLines(input);
            for (String line : lines.subList(1, lines.size())) {
                String[] c = line.split(",");
                try {
                    byCity.merge(c[1], Integer.parseInt(c[2]), Integer::sum);
                } catch (NumberFormatException e) {
                    skipped++;
                }
            }

            try (BufferedWriter w = Files.newBufferedWriter(report)) {
                w.write("Sales report for 15 Aug 2024");
                w.newLine();
                int grand = 0;
                for (var e : byCity.entrySet()) {
                    w.write(String.format("%-10s Rs %,7d", e.getKey(), e.getValue()));
                    w.newLine();
                    grand += e.getValue();
                }
                w.write(String.format("%-10s Rs %,7d", "TOTAL", grand));
                w.newLine();
                w.write("Skipped rows: " + skipped);
            }

            System.out.println(Files.readString(report));
        } finally {
            Files.deleteIfExists(input);
            Files.deleteIfExists(report);
            Files.deleteIfExists(dir);
        }
    }
}

Output

Sales report for 15 Aug 2024
Bengaluru  Rs   3,998
Chennai    Rs   2,099
Hyderabad  Rs     650
TOTAL      Rs   6,747
Skipped rows: 1

Production Tips

  • Always use try-with-resources for readers, writers and Files.lines streams.
  • Write to a temporary file first and then Files.move it into place, so readers never see a half-written report.
  • Validate every row and count or log bad rows instead of crashing the whole job.
  • For very large files, stream them with Files.lines instead of loading everything.