Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 657
dragonmnl Avatar asked May 31 '12 09:05

dragonmnl


3 Answers

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());
like image 181
Joel Westberg Avatar answered Nov 15 '22 08:11

Joel Westberg


The JVM will look for the file in the current working directory.

Where this is depends on your IDE settings (how your program is executed).

To figure out where it expects file.txt to be located, you could do

System.out.println(new File("."));

If it for instance outputs

/some/path/project/build

you should place file.txt in the build directory (or specify the proper path relative to the build directory).

like image 43
aioobe Avatar answered Nov 15 '22 07:11

aioobe


Try:

File f = new File("./build/classes/file.txt");
like image 43
Eng.Fouad Avatar answered Nov 15 '22 07:11

Eng.Fouad