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

5

5

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

Pedicle answered 31/5, 2012 at 9:3 Comment(2)
I think your question is fully answered by the accepted answer of this question: #1480898Thoroughwort
In addition to Hassan's comment, I always include f.getAbsolutePath() in my error messages about files so that I know what file I'm talking about.Castaway
U
7

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());
Unmeasured answered 31/5, 2012 at 9:10 Comment(0)
R
2

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).

Rappee answered 31/5, 2012 at 9:7 Comment(2)
thank you. Now I try. But a question: If I compile the code with Netbeans (for example) and then one person execute it in windows command line in another computer will it works correctly or may give the same problem?Pedicle
It will work fine as long as you provide the the file-path relative to the current working directory (and as long as the windows user launches the program from the same path).Rappee
R
1

Try:

File f = new File("./build/classes/file.txt");
Rodgers answered 31/5, 2012 at 9:5 Comment(0)
W
0
Use "." to denote the current directory

String path = "./build/classes/file.txt";

File f = new File(path);
Wilheminawilhide answered 31/5, 2012 at 9:47 Comment(0)
S
0

File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder

Sutler answered 20/7, 2020 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.