/**
* This program
shows the use of a try/catch block to
* handle the any exception that arises.
The .getMessage()
* method of the Exception class tells
what went wrong. It uses
* the
"grand daddy Exception class which should only
* be used in this course to determine
WHAT exception occurred.
* THINGS TO
EXPERIMENT WITH
* declare an array of 4 items and read
from the file
* fnfe.txt which contains 5 items. and see what happens.
*
* @author ????
- modified by Elizabeth Adams
* @version ???
- September 5, 2008
*/
import java.util.Scanner;
import java.io.*;
public class ReadFromFile4
{
public static void main (String []
args)
{
String fileName; // will hold the name of the file to
be read from
Scanner fileScanner;
Scanner keyboard; //
int value;
// needed to get filename from
user sitting at keyboard
keyboard = new Scanner (System.in);
System.out.println
//
prompt to user at keyboard
(" Please enter name of
file holding integers and hit return ");
fileName =
keyboard.nextLine();
System.out.println // echo of user's input
(" The
name of the file you want to open is " + fileName);
try
// note that
another Scanner object is needed to read from
// the file. the keyboard Scanner
object read from the keyboard.
{
fileScanner = new Scanner (new File (fileName));
// if file is
found, read numbers from file as long as there are
// numbers in the file
while (fileScanner.hasNextInt())
{
value = fileScanner.nextInt();
System.out.println // echo the values picked up
(" The value you got from the file
is " + value);
} // end while
}
// end try
catch (Exception e) // catches any
exception in the Exception class
{
// feedback to programmer telling
which Exception occurred
System.out.println(e.getMessage());
}
// end catch
} // end main
} // end clas