简体   繁体   中英

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

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());

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

尝试:

File f = new File("./build/classes/file.txt");
Use "." to denote the current directory

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

File f = new File(path);

文件对象加载,在其当前目录中寻找匹配项....直接在您的项目文件夹中,您的类文件不是在您的源文件中加载的.....将文件直接放在项目文件夹中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM