Read Data from a File into an ArrayList
File Class
We can use the File class to represent a file.
Constructor
We can create a File object using a String that contains the file path.
File dataFile = new File(filepath);
If the file pile has backslash characters (\), you will need to use two, since this is an escape character.
Scanner Class
You can use the Scanner class to read from a file.
Constructor
The Scanner constructor can be used to create a Scanner object with a File object as the parameter.
Scanner fileScanner = new Scanner(dataFile);
When we create a Scanner object with a File, it is possible for an exception to be thrown if the file path doesn't exist. A try..catch statement can be used.
try(Scanner fileScanner = new Scanner(dataFile)) {
//statements if the dataFile path exists
} catch (FileNotFoundException error) {
//statements if the file isn't found
}
Scanner Methods
hasNextLine()returnstrueif there is another line in the input of this scanner andfalseotherwise.nextLine()advances the scanner past the current line and returns the input that was skipped.
try(Scanner fileScanner = new Scanner(dataFile)) {
ArrayList<String> lines = new ArrayList<>();
while (fileScanner.hasNextLine()) {
lines.add(fileScanner.nextLine());
}
//iterate over lines and separates each entry by comma,
//create an object to represent the line with the appropriate data,
//add the object to an array that represents the data as objects
} catch (FileNotFoundException error) {
print("An error has occured.");
}