/** * this program shows how easy it is to write code when the
comments are descriptive enough and illustrates the
* use of Scanner, Files, and try/catch blocks * @author Elizabeth Adams * @version 1.3 September 9, 2008 */ |
import java.util.Scanner;
import java.io.*;
public class FilePlay
{
public static void
main (String [] args)
{
String fileName;
Boolean found;
Scanner keyboard;
FileReader myFileReader;
keyboard = new
Scanner (System.in);
// ask user for the name of the input
file
2 System.out.println ( Please
enter the name of your file );
// pick up the user's filename
3
fileName = keyboard.next() OR
fileName = keyboard.nextLine(); |
//
want to open that file for input but its possible that the file name may not
be correct and that the file will not // be found. Will
want to loop until it is found
//
Use the Boolean variable named found as a flag set it to false
4
found = false; |
// while the file is not found loop
5
while (!found) |
{
// try to open the file
6
try |
{
7 myFileReader = new FileReader (fileName); OR myFileReader = new
FileReader (new File (fileName)); |
// if the file is opened, then it
has been found set
the Boolean variable to true
8
found = true;
|
} // end try
// catch the exception thrown if the
file is not found
9 catch
(FileNotFoundException fnfe) |
{
// ask the user to re-enter the name.
10
System.out.println ( Please
re-enter your filename, the file was not found ); fileName = keyboard.nextLine()
OR fileName = keyboard.next(); |
}
// end catch
} // end while
} // end main
} // end class