我正在尝试在while循环中编写一个未找到文件的异常代码,以便程序继续提示用户输入该文件(test.txt)。我在while循环中写了一个try / catch块。但是,当我删除输入文件(test.txt)时,程序应该捕获此错误并打印“错误,无法找到'test.txt'文件,请再试一次:”并允许用户输入另一个文件名。但是,程序崩溃并给我一个FileNotFoundException。
答案 0 :(得分:0)
在你的代码中,有两行会引发你没有捕获的FileNotFoundException
:
// scanner and printwriter objects for reading text file
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
您可以使用以下内容替换它们,并且代码(应该)可以正常工作。
Scanner in = null;// Initialize to null, so they don't raise warnings.
PrintWriter out = null;
try { // Surround with try/catch to get the exception
in = new Scanner(correctInputfile);
out = new PrintWriter(outputName);
}catch(FileNotFoundException e){
/*TODO: something about the exception here!
Make sure the Scanner and PrintWriter get
properly initialized with valid file names.*/
}
答案 1 :(得分:0)
在这种情况下,最好是请求许可而不是宽恕(例如,在尝试阅读之前检查文件是否存在)。
File file = new File("test_input.txt");
if (file.exists()) {
FileReader fileReader = new FileReader(file);
}
答案 2 :(得分:0)
您应该为扫描仪添加另一个try和catch
// prompt user for name for output textfile
System.out.println();
System.out.print("What would you like to call your output file: ");
String outputName = inputReader.nextLine();
// scanner and printwriter objects for reading text file
try {
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
// messages triggered by successful location of files.
if (fileName.equalsIgnoreCase(("test_input.txt"))) {
// code logic
}
} catch (FileNotFoundException ex) {
System.out.println();
System.out.println("***** ERROR *****");
System.out.println("\nCannot locate the input file " + "'" + fileName + "'" + "on your computer - please try again.");
System.out.print("\nInput file name (from your computer): ");
}