/home/wpollock1/public_html/AJava/ParseCSV.java
package com.wpollock;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.List;
/**
* Parses simple CSV files: comma is field delimiter, newline is the record
* delimiter, fields are text without commas. Each line has three fields:
* a date in DD-MM-YYYY format, an amount (a double), and a description.
*
* This is a poorly designed class, but it does show how to read and
* parse a CSV file. Consider how to refactor this one class into several
* to improve cohesion, coupling, clarity, and testability.
*/
public class ParseCSV {
public static void main (String[] args) {
Path path;
List<String> lines = null;
try {
// This is how you refer to a file in .../src/{main,test}/resources
// with Maven, which uses the right version automatically.
// Note the leading slash:
path = Paths.get(
ParseCSV.class.getResource("/data.csv").toURI() );
lines = Files.readAllLines(path);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
assert lines != null;
System.out.printf("The total of the transactions is $%,4.2f.%n",
calculateTransactionsTotal(lines));
}
private static double calculateTransactionsTotal(List<String> lines) {
double total = 0.00;
for (final String line: lines) {
final String[] field = line.split(",");
final double amount = Double.parseDouble(field[1]);
total += amount;
}
return total;
}
}