【问题标题】:How do I display an error message if a file is not found?如果找不到文件,如何显示错误消息?
【发布时间】:2019-12-01 06:14:35
【问题描述】:

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

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

【问题讨论】:

  • 您遇到什么错误?为什么你认为它不起作用?您没有收到“文件 mot Found”消息吗?
  • 嗯,这里的代码是写入到一个文件,而不是读取。 write 到不存在的文件不是错误;如果该文件以前不存在,则会创建它。
  • 我一直得到的错误是:线程“main”java.io.FileNotFoundException中的异常:Data.txt(系统找不到指定的文件)
  • 定义“不起作用”。

标签: java file error-handling message


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-21
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 2013-12-25
      • 2012-05-31
      相关资源
      最近更新 更多