“线程中的异常”;“主要”;java.io.FileNotFoundException:错误
我正在使用Eclipse编译和运行我的java代码 这是我得到的错误。“线程中的异常”;“主要”;java.io.FileNotFoundException:错误,java,eclipse,file-io,exception-handling,java.util.scanner,Java,Eclipse,File Io,Exception Handling,Java.util.scanner,我正在使用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.<init>(Unknown
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.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at helloworld.main(helloworld.java:9)
File.txt我在项目的同一文件夹中创建了file.txt。您的文件应直接位于项目文件夹下,而不是任何其他子文件夹中 因此,如果您的项目文件夹是
MyProject
,它的文件夹结构(虽然不完整)应该如下所示:-
MyProject +- src +
| |
| +-- Your source file
+- file.txt
它不应位于src文件夹下的
或者,您可以提供以下相对于项目文件夹的路径,以搜索src文件夹中的文件
:-
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"
它对我有效。您的文件是否直接位于您的项目文件夹下?它位于SCR下,我也将其中一个放在bin下,因为SCR不起作用。请尝试打印新文件(“file.txt”)。exists()
它是否生成true
?如果没有,请尝试打印新文件(“File.txt”)。getAbsoluteFile()
这是您所期望的吗?它正在执行此操作的同一目录中查找File.txt文件。如果是来自IDE,检查工作目录设置为什么。尝试将它放在与.class文件相同的文件夹中。+ 1考虑使用前斜杠<代码> /<代码>而不是向后斜线。我没猜到。
"C:\\Users\\mogli\\docs\\file.txt"