Java Program to Read a CSV File and Calculate the Total
CSV files are everywhere. This program reads a small sales file, skips the header, ignores bad lines, and shows the total and the average.
Program
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Main {
record Sale(String item, int quantity, double price) {
double amount() { return quantity * price; }
}
public static void main(String[] args) throws IOException {
Path file = Path.of("sales.csv");
Files.write(file, List.of(
"item,quantity,price",
"Pen,10,5.50",
"Book,2,250",
"Bag,1,899.99",
"Broken line",
"Notebook,abc,40"));
List<Sale> sales = Files.readAllLines(file).stream()
.skip(1) // header
.map(Main::parse)
.filter(s -> s != null)
.toList();
double total = sales.stream().mapToDouble(Sale::amount).sum();
System.out.println("Valid rows: " + sales.size());
sales.forEach(s -> System.out.printf("%-10s %8.2f%n", s.item(), s.amount()));
System.out.printf("Total: %.2f%n", total);
System.out.printf("Average per row: %.2f%n", total / sales.size());
}
static Sale parse(String line) {
String[] p = line.split(",");
if (p.length != 3) {
System.out.println("Skipped (wrong columns): " + line);
return null;
}
try {
return new Sale(p[0].trim(), Integer.parseInt(p[1].trim()), Double.parseDouble(p[2].trim()));
} catch (NumberFormatException e) {
System.out.println("Skipped (bad number): " + line);
return null;
}
}
}
Output
Skipped (wrong columns): Broken line
Skipped (bad number): Notebook,abc,40
Valid rows: 3
Pen 55.00
Book 500.00
Bag 899.99
Total: 1454.99
Average per row: 485.00
Notes
split(",")is fine for simple files. If a value can contain a comma inside quotes, use a CSV library such as Apache Commons CSV.- We use a
recordfor a row, and a stream to process the lines. See Java Records and Java Streams. - For huge files, use
Files.lines()in a try with resources and process one line at a time. See Java File Handling.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |