/**
* This program
shows the simplest, cleanestuse of
* a try/catch block to catch the error
that is found
* when the user enters the name of a
file that the
* system can not find.
*
* @author ???? - modified by Elizabeth
Adams
* @version ???
- September 5, 2008
*/
import java.util.Scanner;
import java.io.*;
public class ReadFromFile
{
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
// specific existing Exception
to use when file user
// wants can not be found
catch (FileNotFoundException
fnfe)
{
System.out.println
(" the file you wanted to open " + fileName +
" could not be found ");
} // end catch
} // end main
} // end
class