diff --git a/src/main/java/millions/StockInformationCSVReader.java b/src/main/java/millions/StockInformationCSVReader.java new file mode 100644 index 0000000..7b36a63 --- /dev/null +++ b/src/main/java/millions/StockInformationCSVReader.java @@ -0,0 +1,38 @@ +package millions; + +import java.io.*; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + +public class StockInformationCSVReader { + private final File file; + + public StockInformationCSVReader(File file) { + this.file = file; + } + + public List readFile() { + List stocks = new ArrayList<>(); + try (Reader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader)) { + List 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)); + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } + return stocks; + } +} \ No newline at end of file diff --git a/src/main/java/millions/StockInformationCSVWriter.java b/src/main/java/millions/StockInformationCSVWriter.java new file mode 100644 index 0000000..f36dd18 --- /dev/null +++ b/src/main/java/millions/StockInformationCSVWriter.java @@ -0,0 +1,34 @@ +package millions; + +import java.io.*; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +public class StockInformationCSVWriter { + private final List stocks; + private final File destinationFile; + + public StockInformationCSVWriter(List stocks,File destinationFile) { + this.stocks = stocks; + this.destinationFile = destinationFile; + } + + public void write() { + StringBuilder builder = new StringBuilder(); + for (Stock stock : stocks) { + builder.append(stock.getSymbol()); + builder.append(","); + builder.append(stock.getCompany()); + builder.append(","); + // Unsure if price history or just latest price should be saved + builder.append(stock.getSalesPrice().toPlainString()); + builder.append("\n"); + } + try (FileWriter writer = new FileWriter(destinationFile); BufferedWriter bufferedWriter = new BufferedWriter(writer)) { + bufferedWriter.write(builder.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } +}