/**
* This program
shows the use of a try/catch block to
* handle the exception that arises when
the input file
* name entered by the user can not be
found. It has
* two catch blocks –
one which is needed and one which
* is not
* @author ???? -
modified by Elizabeth Adams
* @version ???
- September 5, 2008
*/
import java.util.Scanner;
import java.io.*;
public class
ReadFromFile6
{
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
// the following catch block is silly because there is not
// array in this program but it will
not cause any error
catch (ArrayIndexOutOfBoundsException aioobe)
{
System.out.println ("Array
index went out of bounds ");
} // end catch
// this is the catch statement that is needed for this program
// not to bomb
catch (FileNotFoundException
fnfe)
{
System.out.println
(" The
file you wanted to open was not found ");
} // end catch
} // end main
} // end class