Java Reference
In-Depth Information
prompting until the user does enter a legal name. The File class has a method called
canRead that you can use to test whether a file exists and can be read. You can print
an error message each time the file can't be read, until you get a good file name. This
situation turns out to be a fencepost problem. If you end up prompting the user n
times, you'll want to produce n - 1 error messages. You can use the classic fencepost
solution of prompting for the file name once before the loop:
System.out.print("input file name? ");
File f = new File(console.nextLine());
while (!f.canRead()) {
System.out.println("File not found. Try again.");
System.out.print("input file name? ");
f = new File(console.nextLine());
}
This code could be included in your main method, but there is enough code here
that it makes sense to put it in its own method. Because it is prompting the user for
input, the code requires a Scanner for reading from the console. It can return a
Scanner that is tied to the input file to process.
When you try to create a method that includes this code, you again run into the
problem of checked exceptions. Even though we are being very careful to make sure
that the file exists and can be read, the Java compiler doesn't know that. From its
point of view, this code might throw an exception. You still need to include a throws
clause in the method header, just as you've been doing with main :
public static Scanner getInput(Scanner console)
throws FileNotFoundException {
System.out.print("input file name? ");
File f = new File(console.nextLine());
while (!f.canRead()) {
System.out.println("File not found. Try again.");
System.out.print("input file name? ");
f = new File(console.nextLine());
}
// now we know that f is a file that can be read
return new Scanner(f);
}
Here is a variation of the CountWords program that prompts for a file name:
1 // Variation of CountWords that prompts for a file name.
2
3 import java.io.*;
4 import java.util.*;
 
Search WWH ::




Custom Search