java如果找不到文件,如何显示错误消息?
我编写了一个程序来读取一个特定的文件,我想知道如果找不到该文件,我将如何显示自定义消息。我目前所做的不起作用,有人能解释一下原因吗
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();
# 1 楼答案
当具有指定路径名的文件不存在时,FileInputStream、FileOutputStream和RandomAccessFile构造函数将引发此异常。如果文件确实存在,但由于某些原因无法访问,例如试图打开只读文件进行写入时,这些构造函数也会抛出该文件
检查此链接https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
# 2 楼答案
若要显示“未找到文件”异常,请将catch块更改为此