Reading a File
How to read a CSV file line by line with a `Scanner` and turn each line into an object in a list.
Apprentice · Java · Updated
When you think of reading a file you should think of the file as a very simple text database. Your end goal is to load its contents into your application's memory.
In your DAOs, when you connect to a database you define your query and execute the query.
You then loop through every row in the result set and read the value of each column in each row.
We follow the same pattern when reading a file.
- Specify the file path and open the file
- Loop through and read each line in the file
- Process the data or create an object
- Close the file
Let's look at an example. We will read the contents of a csv file.
student_grades.csv
firstname,lastname,gpa
Emily,Wilson,3.91
Sarah,Johnson,3.31
John,Smith,2.55
Anna,Williams,3.02
Jane,Garcia,3.96
David,Jones,3.24
Laura,Brown,2.97
Chris,Martinez,3.4
Michael,Davis,2.43
James,Miller,3.85
Following is the code to read the rows of this file and store each row in an ArrayList<Student>.
List<Student> students = new ArrayList<Student>();
// create a file object for the file path
File file = new File("student_grades.csv");
// open the file for reading
try(Scanner reader = new Scanner(file))
{
// skip the first line because it is the header
reader.nextLine();
// loop through each line in the file
while(reader.hasNextLine())
{
// read the line and convert its contents to a student object
var line = reader.nextLine();
var columns = line.split(",");
String firstName = columns[0];
String lastName = columns[1];
double gpa = Double.parseDouble(columns[2]);
var student = new Student(firstName, lastName, gpa);
// add the student to the ArrayList
students.add(student);
}
}
catch(FileNotFoundException ex)
{
System.out.println("Could not find the file: " + ex.getMessage());
}
Do it: turn the grade file's lines into students
The grade book reads student_grades.csv and needs a Student for each line. Opening the file is the Scanner's job; the real work is what happens to each line. The box has no files, so the lines come to your method as a List<String>, exactly as reader.nextLine() would read them, one after another.
Student is given at the bottom of the file, with getFirstName(), getLastName() and getGpa().
The method gets one value:
lines: the file's lines. The first line is always the header,firstname,lastname,gpa. Every line after it is a first name, a last name and a GPA, separated by commas, except perhaps a blank line,"", at the very end, which many editors leave behind.
For example:
List<String> lines = List.of("firstname,lastname,gpa", "Emily,Wilson,3.91", "Jane,Garcia,3.96");
| Line | Columns | What happens |
|---|---|---|
firstname,lastname,gpa |
The header: skipped | |
Emily,Wilson,3.91 |
Emily, Wilson, 3.91 |
A student: Emily Wilson, GPA 3.91 |
Jane,Garcia,3.96 |
Jane, Garcia, 3.96 |
A student: Jane Garcia, GPA 3.96 |
So readStudents(lines) returns a list of 2 students: Emily Wilson with a GPA of 3.91, then Jane Garcia with 3.96.
Your job: write the method readStudents(List<String> lines) so it returns a List<Student>, in the file's order.
- Skip the first line, the header.
- Skip a blank line (
""). - Split each other line at its commas, and make a
Studentfrom its three columns: first name, last name, and the GPA as adouble. - A file with only the header gives an empty list.
Practiced live on the lesson page: write the Java right there and check it.