From ca250b371873952bf5d4666d9c5e77c79d31e584 Mon Sep 17 00:00:00 2001 From: Anthony Berg Date: Tue, 15 Oct 2024 15:08:31 +0200 Subject: [PATCH] feat: add class to read filestream --- src/ReadFile.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/ReadFile.java diff --git a/src/ReadFile.java b/src/ReadFile.java new file mode 100644 index 0000000..d947330 --- /dev/null +++ b/src/ReadFile.java @@ -0,0 +1,34 @@ +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +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 + * @return The contents of the file + */ + public List open(String filename) throws IllegalArgumentException, FileNotFoundException { + // Check that the filetype is correct, otherwise, throw IllegalArgumentException + if (!filename.endsWith(".txt")) { + throw new IllegalArgumentException("The filename is not a .txt format"); + } + + // Open the file that was defined + File file = new File(filename); + Scanner reader = new Scanner(file); + + // List for all the separate lines on the database + List data = new ArrayList<>(); + + // Go through all the lines in the file and append them to the list `data` + while (reader.hasNextLine()) { + String currentData = reader.nextLine(); + data.add(currentData); + } + + return data; + } +}