Skip to content

Fixed logic in FileHandler to make it OS independent and added more tests #31

Merged
merged 4 commits into from
Apr 15, 2026
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 79 additions & 69 deletions millions/src/main/java/no/ntnu/gruppe53/FileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,125 +4,135 @@
import java.io.BufferedWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
* Handles file operations for the application.
* Handles reading and writing of .csv files for stocks.
*/

public class FileHandler {

/**
* Writes a list of {@link Stock}s to a text-file. Class is structed for {@code .csv} files.
* Writes a list of {@link Stock}s to a CSV file in UTF-8 encoding.
*
* @param stockList the list of stocks to be converted to text
* @param path output path for the file
* @param filename name of the file (not including extension)
* @param stockList the list of stocks to be written
* @param path directory path for the file
* @param filename name of the file (without or with .csv extension)
* @throws IllegalArgumentException if stockList, path, or filename is null, or if stockList is empty
*/
public static void writeStocksToFile(List<Stock> stockList, String path, String filename) {
String pathString = path + filename;
Path filePath = Paths.get(pathString);

try (BufferedWriter writer = Files.newBufferedWriter(filePath, Charset.defaultCharset())) {
if (!Files.exists(filePath)) {
Files.createDirectories(filePath);
if (stockList == null) throw new IllegalArgumentException("StockList cannot be null");
if (path == null || path.isBlank()) throw new IllegalArgumentException("Path cannot be null or blank");
if (filename == null || filename.isBlank()) throw new IllegalArgumentException(
"Filename cannot be null or blank");


path = path.trim();
filename = filename.trim();
String filenameWithExtension = filename.endsWith(".csv") ? filename : filename + ".csv";

Path filePath = Paths.get(path, filenameWithExtension);

Path dirPath = filePath.getParent();
if (!Files.exists(dirPath)) {
try {
Files.createDirectories(dirPath);
} catch (IOException e) {
System.out.println("ERROR: Could not create directories.");
e.printStackTrace();
return;
}
}

try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8)) {
writer.write("#Ticker,Name,Price");
writer.newLine();
writer.newLine();

for (Stock stock : stockList) {
String line = String.join(",", stock.getSymbol(), stock.getCompany(),
if (stock == null) continue;
String line = String.join(",",
stock.getSymbol(),
stock.getCompany(),
stock.getSalesPrice().toString());
writer.write(line);
writer.newLine();
}

} catch (IOException e) {
System.out.println("ERROR: Something went wrong while writing the csv file.");
System.out.println("Message: " + e.getMessage());
System.out.println("ERROR: Something went wrong while writing the CSV file.");
e.printStackTrace();
}
}

/**
* Reads a .csv file and converts it to a list of {@code Stock} objects.
* Reads a CSV file and converts it to a list of {@link Stock} objects.
*
* @param path path to the file to be read
* @param filename name of the file to be read (including extension)
* @return a list of {@code Stock} objects converted from text
* @param path directory path of the CSV file
* @param filename CSV file name (with or without .csv extension)
* @return list of Stock objects
*/
public static List<Stock> readStocksFromFile(String path, String filename) {
List<Stock> stocks = new ArrayList<>();
String pathString = path + filename;
Path filePath = Paths.get(pathString);
if (path == null || path.isBlank()) {
throw new IllegalArgumentException("Path cannot be null or blank.");
}
if (filename == null || filename.isBlank()) {
throw new IllegalArgumentException("Filename cannot be null or blank.");
}

path = path.trim();
filename = filename.trim();
String filenameWithExtension = filename.endsWith(".csv") ? filename : filename + ".csv";

Path filePath = Paths.get(path, filenameWithExtension);

if (!Files.exists(filePath)) {
System.out.println("ERROR: File not found: " + filePath.toAbsolutePath());
return stocks;
}

try (BufferedReader reader = Files.newBufferedReader(filePath, Charset.defaultCharset())) {
try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
String line;
String symbol;
String name;
BigDecimal price;

while ((line = reader.readLine()) != null) {
symbol = null;
name = null;
price = null;
int counter = 0;
String trimValue = line.trim();
line = line.trim();

if (trimValue.isBlank() || (line.charAt(0) == '#')) {
if (line.isBlank() || line.startsWith("#")) continue;

String[] values = line.split(",", -1);
if (values.length != 3) {
System.out.println("ERROR: Bad line in CSV (expected 3 values): " + line);
continue;
}

String[] values = line.split(",");
String symbol = values[0].trim();
String name = values[1].trim();
BigDecimal price;

if (values.length != 3) {
System.out.println("ERROR: Bad line in csv: ");
System.out.print(line);
System.out.println("There should be 3 values total: " +
"symbol, name, price.");
try {
price = new BigDecimal(values[2].trim());
} catch (NumberFormatException e) {
System.out.println("ERROR: Price is not a valid number: " + values[2]);
continue;
}

for (String value : values) {
trimValue = value.trim();

switch (counter) {
case 0:
symbol = trimValue;
break;
case 1:
name = trimValue;
break;
case 2:
try {
price = new BigDecimal(trimValue);
}
catch (NumberFormatException e) {
System.out.println("ERROR: Not a number. Last column in .csv file " +
"needs to be the price of the stock (number). Skipping...");
price = null;
break;
}
}
counter++;
}
if (symbol == null || symbol.isBlank() || name == null || name.isBlank() ||
price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
if (symbol.isBlank() || name.isBlank() || price.compareTo(BigDecimal.ZERO) <= 0) {
System.out.println("ERROR: Invalid stock data, skipping: " + line);
continue;
}

stocks.add(new Stock(symbol, name, price));
}

} catch (IOException e) {
System.out.println("ERROR: Something went wrong while reading the CSV file.");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("ERROR: Something went wrong while reading the csv file.");
System.out.println("Message: " + e.getMessage());
}

return stocks;
}
}
}
Loading