File I/O

In this lab we will be using a Scanner object to read from a text file. If you need to remember how to read in command line arguments in Eclipse, click here. Initialize a FileInputStream with the string args[0] and initialize the Scanner with the FileInputStream. We will read information about students from the file students.txt. This text file will contain the name of the student and their ID number in the format:

name id

The first line of the file contains the number of student records in the file. This will enable us to decide on the size of data structure to use to store the students' information.

There are many ways to handle reading from a file, but the basic steps needed to do so are:

  1. Open the file. This is done implicitly by creating a stream object.
  2. Read through the file (line-by-line, character-by-character, etc) until you reach the end-of-file (EOF) character.
  3. Close the file.

There are many ways to do the second step, including handling detection of the EOF character.
  1. In the case of this lab, the number of records is given at the beginning of the file. So you could simply read the number of lines specified in the beginning of the file. This, however, is unrealistic, since most files do not specify how many records they contain.
  2. Keep looping until the program detects the end of the file, reading the next item on each iteration. This is how file I/O is done in most languages and it is what you will implement in this lab. Some Scanner functions can make this easier.
  3. In Java, there is an EOFException. You could enclose your file reading logic in a try-catch block that reads records from your file until this exception is caught, but relying on this is bad practice. A program that runs correctly with normal input should not be expected to throw exceptions.