Skip to content

Commit

Permalink
Moved parsing of stock information to csvStockFileParser and added fo…
Browse files Browse the repository at this point in the history
…rmat verification to allow for other file formats in the future
  • Loading branch information
Nikollai committed Apr 12, 2026
1 parent e271319 commit 84c1a03
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 17 deletions.
40 changes: 40 additions & 0 deletions src/main/java/millions/controller/CSVStockFileParser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package millions.controller;

import millions.model.Stock;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CSVStockFileParser {
private List<String> lines;

public CSVStockFileParser(List<String> lines) {
if (verifyCSV(lines)) {
this.lines = lines;
}
else {
// throw file format error
}
}

// returns true if all entries have exactly 3 data points
private static boolean verifyCSV(List<String> lines) {
return lines.stream()
.filter(l -> !(l.startsWith("#") || l.isEmpty()))
.anyMatch(l -> l.split(",").length != 3);
}

public List<Stock> parse() {
List<Stock> stocks = new ArrayList<>();
lines.forEach(l -> {
String[] split = l.split(",");
String symbol = split[0];
String company = split[1];
BigDecimal price = new BigDecimal(split[2]);
stocks.add(new Stock(symbol, company, price));
});
return stocks;
}
}
21 changes: 4 additions & 17 deletions src/main/java/millions/controller/StockInformationReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,13 @@ public StockInformationReader(File file) {
this.file = file;
}

public List<Stock> readFile() {
List<Stock> stocks = new ArrayList<>();
public List<String> readFile() {
List<String> lines = new ArrayList<>();
try (Reader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader)) {
List<String> lines = bufferedReader.readAllLines();
for (String line : lines) {
// Skips comment and blank lines
if ( !(line.startsWith("#") || line.isEmpty()) ) {
String[] data = line.split(",");
// Ensures only fields of the correct length are read
if (data.length == 3) {
String symbol = data[0];
String company = data[1];
BigDecimal price = new BigDecimal(data[2]);
stocks.add(new Stock(symbol, company, price));
}
}
}
lines = bufferedReader.readAllLines();
} catch (IOException e) {
e.printStackTrace();
}
return stocks;
return lines;
}
}

0 comments on commit 84c1a03

Please sign in to comment.