Skip to content

Commit

Permalink
add ability to read and write from file
Browse files Browse the repository at this point in the history
  • Loading branch information
einaskoi committed Mar 23, 2026
1 parent 76d3541 commit 4ea21f9
Show file tree
Hide file tree
Showing 3 changed files with 585 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/main/java/edu/ntnu/idi/idatt2003/gruppe42/Millions.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

public class Millions {
public static void main(String[] args) {
System.out.println("PLEASE WORK GIT");
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package edu.ntnu.idi.idatt2003.gruppe42.Model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
* Utility class for handling file data.
* Includes methods for reading and writing from file, as well as parsing stock data into objects.
* Using BufferedReader/BufferedWriter for optimized handling.
*/
public class StockFileHandler {

/**
* Method for parsing stock data into stock objects.
*
* @param path the relative path of the file being parsed (from source root)
* @return list of stock objects parsed from data file
* @throws IOException if file not found
*/
public static List<Stock> readFromFile(Path path) throws IOException {

List<Stock> stocks = new ArrayList<>();

try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path.toFile()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim();

if (line.isEmpty() || line.startsWith("#")) {
continue;
}

String[] parts = line.split(",");

String symbol = parts[0];
String company = parts[1];
BigDecimal salePrice = new BigDecimal(parts[2].trim());

stocks.add(new Stock(symbol, company, salePrice));
}
}
return stocks;
}

/**
* Method for writing stock information to file.
*
* @param path the relative path of the file being parsed (from source root)
* @param stocks list of stock objects to be transcribed to data file
* @throws IOException if file not found
*/
public static void writeToFile(Path path, List<Stock> stocks) throws IOException {

try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("# S&P 500 Companies by Market Cap");
writer.write("\n# Ticker,Name,Price");
writer.newLine();

for (Stock stock : stocks) {
String line = String.format("%s,%s,%s",
stock.getSymbol(),
stock.getCompany(),
stock.getSalesPrice());

writer.write(line);
writer.newLine();
}
}
}
}
Loading

0 comments on commit 4ea21f9

Please sign in to comment.