线程“main”中的异常java.io.FileNotFoundException:错误

时间:2012-11-27 20:17:26

标签: 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 Source)
    at java.util.Scanner.<init>(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。

4 个答案:

答案 0 :(得分:22)

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

因此,如果你的项目文件夹是MyProject,那么它的文件夹结构(虽然不完整)应该是这样的: -

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

它不应该是under src文件夹。


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

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

答案 1 :(得分:5)

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

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

或者如果你在Windows中:

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

答案 2 :(得分:2)

请关注@rohit Jains方法或为文件提供绝对路径,如:

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

答案 3 :(得分:1)

在Windows中尝试提供这样的真实路径

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

它对我有用。

相关问题