java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

dragonmnl picture dragonmnl · May 31, 2012 · Viewed 17.8k times · Source

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.

In the same directory there is the .class file compiled for the following code:

try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
   System.out.println(e);
}

Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:

java.io.FileNotFoundException: file.txt (the system can't find the specified file)

I also tried using "/file.txt" and "//file.txt" but same result.

Thank you in advance for any hint

Answer

Joel Westberg picture Joel Westberg · May 31, 2012

If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.

If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:

URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());