There are a number situation where a FileNotFoundException
may be thrown at runtime.
The named file does not exist. This could be for a number of reasons including:
The named file is actually a directory.
The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:
file.exists()
will tell you if any file system object exists with the given name / pathname.file.isDirectory()
will test if it is a directory.file.canRead()
will test if it is a readable file.This line will tell you what the current directory is:
System.out.println(new File(".").getAbsolutePath());
This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:
System.out.println("The path is '" + path + "'");
Look for unexpected spaces, line breaks, etc in the output.
It turns out that your example code has a compilation error.
I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
If you change your code to the following, it will fix that problem.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.dat");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
Explanation: the Scanner(File)
constructor is declared as throwing the FileNotFoundException
exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException
is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws
clause. The above fix takes the latter approach.