feat: add class to read filestream

This commit is contained in:
Anthony Berg 2024-10-15 15:08:31 +02:00
parent d17d4b73e8
commit ca250b3718

34
src/ReadFile.java Normal file
View File

@ -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<String> 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<String> 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;
}
}