【问题标题】:FileNotFoundException thrown when file exists文件存在时抛出 FileNotFoundException
【发布时间】:2018-03-21 11:57:19
【问题描述】:

当我运行这段代码时,

public static void read_all_lines(){
    String file_name = "input.txt";
    File input_file = new File(file_name);
    Scanner in_file = null;
    try{
        in_file = new Scanner(input_file);
    }
    catch(FileNotFoundException ex){
        System.out.println("Error: This file doesn't exist");
        System.exit(0);
    }
    while(in_file.hasNextLine()){
        String line = in_file.nextLine();
        System.out.println(line);
    }
    in_file.close();
}

这应该读取 .txt 文件中的所有行并将它们打印在抛出 FileNotFoundException 的屏幕上。它捕获它并毫无问题地打印出错误消息。但是文件确实存在,我做了两个文件input和input.txt,但是还是抛出了异常。 This is the file directory where the files and project are.

【问题讨论】:

  • 您是否尝试过使用文件的完整路径,例如 "C:\\folderA\\folderB\\input.txt";
  • 我会立即尝试并返回更新
  • 当前工作目录是什么?
  • 你能解释一下@JohannesKuhn 吗?到目前为止,我们还没有在我的课堂上提到它。如果您的意思是文件的目录,它相当长,但如果是代码,那么恐怕我还没有学会。
  • 相对于您正在执行程序文件的位置,该文​​件位于何处?尝试将System.out.println(System.getProperty("user.dir"); 添加到您的代码中,它会告诉您“工作”目录,这需要与文件所在的目录相同才能正常工作

标签: java netbeans


【解决方案1】:

从外观上看,该程序似乎位于“指导练习 4”文件夹中,而文本文件位于该文件夹之外。如果是这种情况,则将文本文件移动到与程序相同的文件夹中或File input_file = new File("..\\" + file_name); 以引用父目录中的文件。但我建议移动文本文件。

【讨论】:

  • 是的,我明白了这一点,并因此开始憎恨自己。我只是移动了文件作为修复。
【解决方案2】:

文件不在正确的区域。使用 MadProgrammer 提供的System.out.println(System.getProperty("user.dir"));,我找到了程序需要文件的目录并纠正了问题

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • @DanielCheung 这是作者。
  • @JohannesKuhn 哦,您一定知道这是 SO 对审核过程的自动评论。我没有改变它。我的错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多