Getting Input from a File
To open a file for reading: Scanner inFile = new Scanner (file); Scanner constructor - takes a File parameter and provides methods to get individual pieces of data
Scanner class
Provides methods to get the next data in a file. public String next(); public int nextInt(); public double nextDouble(); Provides methods to check whether the next data has a particular type public boolean hasNext(); public boolean hasNextInt(); public boolean hasNextDouble();
- private void readResultFile() throws FileNotFoundException {
- /
/ Open the file.
- Scanner skierFile = new Scanner(new File (RESULTS_FILE));
- /
/ Find out how many skiers are in the file
- int numSkiers = skierFile.nextInt();
- skiers = new Skier[numSkiers];
- /
/ Read the information for each racer.
- for (int i = 0; i < numSkiers; i++) {
- /
/ Line of file is a skier name, followed by 2 doubles, one for each / / race time
- String skierName = skierFile.next();
- double time1 = skierFile.nextDouble();
- double time2 = skierFile.nextDouble();
- skiers[i] = new Skier(skierName, time1, time2);
- skierList.append(skiers[i].toString() + "\n");
- }
- skierFile.close();
- }