feat: add path argument for ReadFile

This commit is contained in:
Anthony Berg 2024-10-17 18:24:17 +02:00
parent 5fffaa6e45
commit d1ba0f9d84
2 changed files with 14 additions and 9 deletions

View File

@ -1,3 +1,4 @@
import java.nio.file.Path;
import java.util.*;
public class Main {
@ -14,7 +15,7 @@ public class Main {
// System.out.println(Arrays.toString(args));
// Get the data from the file
List<String> data = ReadFile.open("example.txt");
List<String> data = ReadFile.open(Path.of("example.txt"));
// Gets a map with the total occurrences for each domain
Map<String, Integer> domains = getDomainTotal(data);

View File

@ -1,5 +1,7 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
@ -7,22 +9,24 @@ import java.util.Scanner;
public class ReadFile {
/**
* Opens a file and returns a list of all the lines in the file
* @param filename the name of the file with, only allowing a .txt extension
* @param path The path to the file
* @return The contents of the file
*/
public static List<String> open(String filename) {
public static List<String> open(Path path) {
// Check that the filetype is correct, otherwise, throw IllegalArgumentException
if (!filename.endsWith(".txt")) {
if (!path.getFileName().toString().endsWith(".txt")) {
throw new IllegalArgumentException("The filename is not a .txt format");
}
File file = new File(filename);
Scanner reader;
try {
// Open the file that was defined
reader = new Scanner(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
reader = new Scanner(path.toFile());
} catch (InvalidPathException e) {
throw new RuntimeException("Could not find the file: " + e);
}
catch (FileNotFoundException e) {
throw new RuntimeException("Could not open the file: " + e);
}
// List for all the separate lines on the database