Skip to content

Commit

Permalink
Merge pull request #28 from IDATT2003-gruppe06/1-add-support-for-read…
Browse files Browse the repository at this point in the history
…ing-stock-data-from-file

merge reading stock data from json
  • Loading branch information
mohenoen authored Mar 27, 2026
2 parents 49c4952 + 072dbc1 commit a6c0ce1
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/main/java/millions/StockInformationCSVReader.java
Original file line number Diff line number Diff line change
@@ -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<Stock> readFile() {
List<Stock> stocks = 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));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return stocks;
}
}
34 changes: 34 additions & 0 deletions src/main/java/millions/StockInformationCSVWriter.java
Original file line number Diff line number Diff line change
@@ -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<Stock> stocks;
private final File destinationFile;

public StockInformationCSVWriter(List<Stock> 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();
}
}
}

0 comments on commit a6c0ce1

Please sign in to comment.