File Input and Output


The File class




Exercise: Write a program that reads a filename from the user, then reads 10 floating-point numbers from the file and prints their average to the console.


Testing the Token Type


Example:
import java.io.*;
import java.util.*;

public class Test
{
    public static void main(String[] args) throws IOException
    { 
       Scanner scan = new Scanner(new File(args[0]));
       double sum = 0;

       while(scan.hasNextDouble())
       {
          sum += scan.nextDouble();
       }

       System.out.println("Sum: " + sum);
    }
}

Exercise: Write a program that reads a file on integers and prints the average. Ignore any non-integer tokens in the file (just skip over them). Example input file:
2 14    77 3.4 skip this
2



Processing a Line of Text with a Scanner Object


If the data in one line of a text file is complex, we may want to use a separate Scanner object to process it. Example file examData.txt:

Susan 79 88 76
Mac 50 99 84
...


Example:
Scanner scan = new Scanner(new File("examData.txt"));
while(scan.hasNextLine())
{
    String studentLine = scan.nextLine();
    Scanner lineProcess = new Scanner(studentLine);
    while(lineProcess.hasNext())
    {
       String name = lineProcess.hasNext();
       if(name.equals("Scott"))
       {
          // compute average of Scott's grades
          for(int i = 0; i < 3; i++)
          {
             sum += lineProcess.nextInt();
          }
          System.out.println("Scott's average: " + sum/3.0);
       }
    }
...
}


Exercise (Searching a file for a specific line): Write a program that reads a student's name from the keyboard, and given the examData.txt file, prints the student's exam average.

Exercise: Re-do the previous exercise - read the name of the file from the console. Prompt the user for a file name until the entered file exists.



Output to a File





File Paths