【问题标题】:Exception in thread "main" java.io.FileNotFoundException: Error线程“主”java.io.FileNotFoundException 中的异常:错误
【发布时间】:2012-11-27 20:17:25
【问题描述】:

我正在使用 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
我在项目的同一文件夹中创建了 file.txt。

【问题讨论】:

  • 你的文件是直接在你的项目文件夹下吗?
  • 它在SCR下,我也在bin下放了一个,因为scr不起作用。
  • 尝试打印new File("file.txt").exists() 是否产生true?如果没有,请尝试打印new File("file.txt").getAbsoluteFile() 是否符合您的预期?
  • 它在你执行它的同一目录中寻找文件 file.txt。如果是来自 IDE,请检查工作目录的设置。
  • 试着把它和你的 .class 文件放在同一个文件夹下。

标签: java eclipse file-io exception-handling java.util.scanner


【解决方案1】:

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

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

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

它不应该是under src 文件夹。


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

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

【讨论】:

  • 啊,太棒了。没猜到。
【解决方案2】:

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

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

或者如果你在 Windows 中:

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

【讨论】:

    【解决方案3】:

    遵循@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 考虑使用正斜杠 / 而不是反斜杠 \。
    【解决方案4】:

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

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

    它对我有用。

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多