ITEC 120
Reading data from a file

Objectives

After successfully completing this lab you will use the Scanner class to read data from a file and you will gain experience with iterators.

Assignment

Download: FileIO.java, start.txt, scores.txt

Reading lines from a file: start.txt

Scanner

You already know how to use the Scanner class to read input from the keyboard.  The Scanner class can read from several different data sources including Strings and Files

You will use a Scanner to scan lines from a file using two methods: hasNext and nextLine. The nextLine method returns the next line from the file, as a String. The hasNext method tells you if there is another line in the file to read. If you try to read a line from a file that isn't there, you'll get a runtime exception. So you'll always check to see if there is a line to read before you read it:

    while the file has a next line,
        read it (as a String)   

When you reach the end of the file, the hasNext method returns false.

Get started

Start with something simple: Read and print lines from the start.txt file.

Take a look at FileIO.java:

Notice the highlighted lines of code. When working with files, it's possible to encounter problems such as trying to open a file that isn't there or trying to read data past the end of a file. These problems throw exceptions (runtime errors). Because of this, we have to state in our code that these exceptions are a possibility. We'll discuss Exceptions and exception handling in greater detail in two weeks, but for now, understand that if you are going to read from a file using the Scanner class, you must import java.io.*, and state that the method doing the file reading could throw an IOException.

Add code to your FileIO.java to read and print each line from the start.txt file. First, you'll need to create a Scanner to scan a File instead of the keyboard. When we read input from the keyboard, we used:

Scanner scan = new Scanner(System.in);

System.in is the keyboard, and we passed it to the Scanner constructor. To read a file, you must pass a file object to the Scanner constructor instead. (Hey, I wonder if the Scanner class has multiple constructors?)

File is a java class (in java.io), and to create a file we could:

File fileObj = new File("filename.filetype");

In the main method, create a File object for the start.txt file, and pass that to a Scanner. Write a loop to read and print all the lines in the start.txt file.

Processing data in the scores.txt file

Processing Data

Thus far we have read and printed rows of data from the start.txt file. Add code to your file to read and print each line of the scores.txt file.

Usually, we want to do more with the data stored in a file. Often, we need to parse the data contained on a line - break it into smaller pieces and analyze each piece.

Take a look at a row of data from the scores.txt file:

85,70,95,82,75

The data above represents five quiz scores. The data is shown in comma separated values (CSV) format. The comma is the delimiter that separates the scores. Note that there are no spaces in the data, just commas and numbers. CSV is a common import and export format for spreadsheets and databases.

You have read the row of data as a String, and now you must extract each score from the string and represent the score as an integer.

    while the file has a next line,
        read it (as a String) 
        while there is data on the line
            read and process each piece of data 

We can use the Scanner to extract numbers from a string. To do this, create a new Scanner (not the one you used to read lines from the file) and pass the entire line of data, as a String, to the Scanner's constructor. The Scanner has a default delimiter: whitespace. But a CSV file is comma-delimited.

Use the Scanner's useDelimiter method to set the delimiter to a comma (",").

Use the Scanner methods hasNext and nextInt to read all the integers from the line of data.

Print the high score, the low score, and the average score for each row of data.
NOTE: No arrays are needed to do this! Process the data as you go.

Example output:

line: 85,70,95,82,75     // the whole line printed
scores: 85 70 95 82 75   
// each score printed

Add additional code to your loop to save the highest and lowest score and print them on a third line:

line: 85,70,95,82,75
scores: 85 70 95 82 75
high: 95  low: 70

Add additional code to your loop to sum the scores and print the sum on the third line.

line: 85,70,95,82,75
scores: 85 70 95 82 75
high: 95  low: 70  sum: 407

Finally, replace the sum with the average.

line: 85,70,95,82,75
scores: 85 70 95 82 75
high: 95  low: 70  average: 81.4

You've probably noticed that there are a different number of quiz scores on each line. Your program should work regardless of how many quiz scores are on a line, and regardless of how many lines are in the file. This is what an Iterator is good for (with the hasNext and next methods). Add a few lines of quiz scores to your scores.txt file and run your program again.

Submit Your Assignment

Submit FileIO.java to the Lab Submission Folder on D2L.