我正在尝试从我的方法输出文件扫描仪对象。这是一项学校作业,我被特别指示不要抛出任何异常,而是使用 try/catch 代替。该分配要求命令行提示用户输入要扫描的文件。如果该文件不存在,我们应该告诉用户,然后再次提示他们输入文件。如果文件确实存在,则该方法返回扫描该文件的扫描仪对象。
我的代码可以工作,但不干净。它涉及2个方法。这是我到目前为止的代码:
public static Scanner getInputScanner (Scanner console) {
File inputFile = null;
Scanner input = null;
try {
inputFile = getFile(inputFile, console);
input = new Scanner (inputFile);
return input;
} catch (FileNotFoundException e) {
try {
return input = new Scanner (getFile (inputFile, console));
} catch (FileNotFoundException f) {
System.out.println("An error has occured.");
return input;
}
}
}
public static File getFile (File inputFile, Scanner console) {
System.out.println("Enter input file: ");
inputFile = new File (console.nextLine());
while (!inputFile.exists()) {
System.out.println("File does not exist.");
System.out.print("Enter input file: ");
inputFile = new File (console.nextLine());
}
return inputFile;
}
代码的问题是输出如下所示:
输入输入文件:
文件不存在。
输入输入文件:
然后等待用户的输入。不过,我不希望输出在最后一行之前有两行代码。
有人可以解释为什么我的代码输出这两行吗? 另外,是否有更简单的解决方案来获取输入文件而不引发 FileNotFoundException?
谢谢!
最佳答案
如果我理解正确的话, 你的程序在运行时输出这些行, 无论, 您没有机会实际输入文件名。
Enter input file: File does not exist.
然后程序再次询问您:
Enter input file:
而且您不想要上面的前两行,对吧?
例如,如果您收到的扫描仪控制台
中有未读的换行符,则可能会发生这种情况。
你还没有发布那部分代码,
所以很难说,但这是 Scanner
的常见问题。
在调用 getInputScanner 之前,
确保扫描仪控制台
可供使用,
里面没有未读的垃圾。
至于你问题的第二部分, 是的,这可以写得更简单更好,例如:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
关于java - java中如何使用try/catch避免抛出FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33454504/