线程“main”中的exceptionjava.io.FileNotFoundException:错误

我正在使用Eclipse来编译和运行我的java代码。

这是我得到的错误。

Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(Unknown Source) at java.util.Scanner.(Unknown Source) at helloworld.main(helloworld.java:9) 

这是我的代码

 import java.io.File; import java.io.IOException; import java.util.Scanner; public class helloworld { public static void main(String[] args) throws IOException { Scanner KB = new Scanner(new File("file.txt")); while (KB.hasNext()) { String line = KB.nextLine(); System.out.println(line); } } } 

FILE.TXT
我在项目的同一文件夹中创建了file.txt。

您的文件应直接位于项目文件夹下,而不是在任何其他子文件夹中。

所以,如果您的项目文件夹是MyProject ,它的文件夹结构(虽然不完整)应该是这样的: –

 MyProject +- src + | | | +-- Your source file +- file.txt 

它不应该under src文件夹下。


或者,您可以提供相对于项目文件夹的以下路径来搜索src folder中的src folder : –

 new File("src/file.txt"); 

尝试将完整路径传递给文件,例如:

 new File("/usr/home/mogli/file.txt") 

或者,如果你在Windows中:

 new File("C:/Users/mogli/docs/file.txt") 

要么遵循@rohit Jains方法,要么给出文件绝对路径 ,如:

  Scanner KB = new Scanner(new File("C:/JsfProjects/Project/file1.txt")); while (KB.hasNext()) { String line = KB.nextLine(); System.out.println(line); } 

在Windows中尝试给出这样的真实路径

 "C:\\Users\\mogli\\docs\\file.txt" 

它对我有用。