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

Mow*_*gli 9 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)
Run Code Online (Sandbox Code Playgroud)

这是我的代码

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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*ain 23

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

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

MyProject +- src +
          |      |
          |      +-- Your source file
          +- file.txt
Run Code Online (Sandbox Code Playgroud)

它不应该是under src文件夹.


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

new File("src/file.txt");
Run Code Online (Sandbox Code Playgroud)


Ósc*_*pez 5

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

new File("/usr/home/mogli/file.txt")
Run Code Online (Sandbox Code Playgroud)

或者,如果你在Windows中:

new File("C:/Users/mogli/docs/file.txt")
Run Code Online (Sandbox Code Playgroud)