ParseCSV.java

Download ParseCSV.java

 1: package com.wpollock;
 2: 
 3: import java.io.IOException;
 4: import java.net.URISyntaxException;
 5: import java.nio.file.*;
 6: import java.util.List;
 7: 
 8: /**
 9:  * Parses simple CSV files: comma is field delimiter, newline is the record
10:  * delimiter, fields are text without commas.  Each line has three fields:
11:  * a date in DD-MM-YYYY format, an amount (a double), and a description.
12:  *
13:  * This is a poorly designed class, but it does show how to read and
14:  * parse a CSV file.  Consider how to refactor this one class into several
15:  * to improve cohesion, coupling, clarity, and testability.
16:  */
17: public class ParseCSV {
18:     public static void main (String[] args) {
19:         Path path;
20:         List<String> lines = null;
21:         try {
22:             // This is how you refer to a file in .../src/{main,test}/resources
23:             // with Maven, which uses the right version automatically.
24:             // Note the leading slash:
25:             path = Paths.get(
26:                     ParseCSV.class.getResource("/data.csv").toURI() );
27:             lines = Files.readAllLines(path);
28:         } catch (URISyntaxException | IOException e) {
29:             e.printStackTrace();
30:         }
31: 
32:         assert lines != null;
33:         System.out.printf("The total of the transactions is $%,4.2f.%n",
34:                 calculateTransactionsTotal(lines));
35:     }
36: 
37:     private static double calculateTransactionsTotal(List<String> lines) {
38:         double total = 0.00;
39:         for (final String line: lines) {
40:             final String[] field = line.split(",");
41:             final double amount = Double.parseDouble(field[1]);
42:             total += amount;
43:         }
44:         return total;
45:     }
46: }