"main"线程中发生异常:java.io.FileNotFoundException错误。

13

我正在使用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);
        }

    }
}

文件.txt
我已经在项目的同一个文件夹中创建了文件.txt。


你的文件直接放在项目文件夹下面吗? - Rohit Jain
它在SCR下,我也放了一个在bin下,因为SCR不起作用。 - Mowgli
1
尝试打印 new File("file.txt").exists(),它是否返回 true?如果没有,请尝试打印 new File("file.txt").getAbsoluteFile(),它是否符合您的预期? - amit
1
它正在查找与您执行此操作相同的目录中的文件file.txt。如果是从IDE进行操作,请检查工作目录设置。 - jco.owens
尝试将它放在与你的 .class 文件相同的文件夹下。 - sbyd
4个回答

32

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

因此,如果您的项目文件夹名为MyProject,则其文件夹结构(尽管不完整)应如下所示: -

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

应将其放置在src文件夹的外部。


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

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

1
啊,太棒了。没想到。 - gbhall
这个答案帮我省了一整天的时间 @Rohit :-) - Vetrivel PS

6
尝试传递文件的完整路径,例如:
new File("/usr/home/mogli/file.txt")

如果你使用的是Windows操作系统:

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

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

1
考虑使用正斜杠 / 而不是反斜杠 \。 - Eng.Fouad

1
在Windows中,尝试像这样提供真实路径:

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

它对我起作用了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接