如果找不到文件,如何显示错误消息?

我编写了一个程序来读取特定文件,并且想知道如果找不到该文件该如何显示自定义消息。我目前没有的东西,有人可以解释为什么吗?

try {
       //create the file writer
       Fwrite = new FileWriter(file);
       Fwrite.write("Student Name \t\t\t Test Score \t Grade\n");
       for (int i = 0; i < size; i++) {
           Fwrite.write(students[i].getStudentLName() + "," + students[i].getStudentFName() + 
                   " \t\t\t "+ students[i].getTestScore() + " \t\t  " + students[i].getGrade() + "\n");
       }
       Fwrite.write("\n\nHighest Test Score: " + highestScore + "\n");

       Fwrite.write("Students having the highest test score\n");

       //writes the test scores in descending order
       for (int i = 0; i < size; i++) {
           if (students[i].getTestScore() == highestScore) {
               Fwrite.write(students[i].getStudentLName() + ",");
               Fwrite.write(students[i].getStudentFName() + "\n");
           }
       }

   //catches any errors
   } catch (IOException e) {
      System.err.println("File mot Found!");
      e.printStackTrace();
   }
   //try catch method to catch any errors
   System.out.println("File Complete!");
   //close file
   Fwrite.close();
wxp1818118 回答:如果找不到文件,如何显示错误消息?

要显示未找到文件异常,请将捕获块更改为此

catch(FileNotFoundException e){
   e.printStackTrace();
}
,

当具有指定路径名的文件不存在时,FileInputStream,FileOutputStream和RandomAccessFile构造函数将抛出此异常。如果文件确实存在,但由于某种原因而无法访问,例如,当试图打开一个只读文件进行写入时,这些构造方法也会抛出该文件。

检查此链接https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

本文链接:https://www.f2er.com/3000011.html

大家都在问