Java 如果找不到文件,如何显示错误消息?
我编写了一个程序来读取一个特定的文件,我想知道如果找不到该文件,我将如何显示自定义消息。我目前所做的不起作用,有人能解释一下原因吗Java 如果找不到文件,如何显示错误消息?,java,file,error-handling,message,Java,File,Error Handling,Message,我编写了一个程序来读取一个特定的文件,我想知道如果找不到该文件,我将如何显示自定义消息。我目前所做的不起作用,有人能解释一下原因吗 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++) {
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();
试试看{
//创建文件编写器
Fwrite=新文件编写器(文件);
Fwrite.write(“学生姓名\t\t\t考试成绩\t成绩\n”);
对于(int i=0;i
要显示文件未找到异常,请将catch块更改为此
catch(FileNotFoundException e){
e.printStackTrace();
}
当具有指定路径名的文件不存在时,FileInputStream、FileOutputStream和RandomAccessFile构造函数将引发此异常。如果文件确实存在,但由于某些原因无法访问,例如试图打开只读文件进行写入时,这些构造函数也会抛出该文件
检查此链接您遇到了什么错误?你为什么认为它不起作用?你没有收到“File mot Found”消息吗?嗯,这里的代码是写入文件,而不是读取。写入不存在的文件不是错误;如果该文件以前不存在,它将被创建。我一直得到的错误是:线程“main”java.io.FileNotFoundException:Data.txt中的异常(系统找不到指定的文件)定义为“不工作”。