簡體   English   中英

文件存在時引發FileNotFoundException

[英]FileNotFoundException thrown when file exists

當我運行這段代碼時

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,但是仍然拋出異常。 這是文件和項目所在的文件目錄。

文件不在正確的區域。 使用System.out.println(System.getProperty("user.dir")); 由MadProgrammer給定,我找到了程序需要文件的目錄並糾正了問題

從外觀上看,該程序似乎位於“ Guided Exercise 4”文件夾中,其中文本文件位於該文件夾之外。 如果是這種情況,則將文本文件移到與程序相同的文件夾中,或者將File input_file = new File("..\\\\" + file_name); 引用父目錄中的文件。 但我建議移動文本文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM