java - java中如何使用try/catch避免抛出FileNotFoundException

标签 java try-catch filenotfoundexception throws

我正在尝试从我的方法输出文件扫描仪对象。这是一项学校作业,我被特别指示不要抛出任何异常,而是使用 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/

相关文章:

java - 关于Java中别名的问题

asp.net - 在ASP.NET中 try catch 错误处理

ios - '在 swift 3 的 'try' 表达式 [警告] 中没有调用抛出函数

java - 检查对象是否为矩阵

java - 以DecoratorPanel内部的GWT DockLayoutPanel + ScrollPanel为中心

android - 无法在 Android 中打开图像文件 - 找不到文件异常

java - 使用可执行 Jar 时找不到 Spring-Boot 资源

java - Sams Teach Yourself Java in 24 Hours Rogers Cadenhead MP3 第 20 章 MP3 文件错误第六版

java - 游戏中的 Random 与 SecureRandom

java - 如何实现猜谜游戏的自定义异常