简体   繁体   English

文件存在时引发FileNotFoundException

[英]FileNotFoundException thrown when file exists

When I run this code, 当我运行这段代码时

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

That is supposed to read all lines in a .txt file and print them on the screen the FileNotFoundException is thrown. 那应该读取.txt文件中的所有行并将它们打印在抛出FileNotFoundException的屏幕上。 It catches it and prints out the error message with no problem. 它会捕获它,并毫无问题地打印出错误消息。 But the file does exist, I made two files input and input.txt, but the exception is still thrown. 但是文件确实存在,我做了两个文件input和input.txt,但是仍然抛出异常。 This is the file directory where the files and project are. 这是文件和项目所在的文件目录。

The files were not in the right area. 文件不在正确的区域。 Using System.out.println(System.getProperty("user.dir")); 使用System.out.println(System.getProperty("user.dir")); given by MadProgrammer I found what directory the program needed the files in and corrected the issue 由MadProgrammer给定,我找到了程序需要文件的目录并纠正了问题

From the looks of it, the program seems to be in the folder "Guided Exercise 4" where the text files are outside that folder. 从外观上看,该程序似乎位于“ Guided Exercise 4”文件夹中,其中文本文件位于该文件夹之外。 If this is the case then either move the text files into the same folder as the program or File input_file = new File("..\\\\" + file_name); 如果是这种情况,则将文本文件移到与程序相同的文件夹中,或者将File input_file = new File("..\\\\" + file_name); to reference the file in the parent directory. 引用父目录中的文件。 But I would recommend the moving the text files. 但我建议移动文本文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM