在Java中出现两个单独的FileNotFoundException异常

3

我需要两个单独的异常,一个是在缺少.pro文件时抛出,另一个是在缺少.cmd文件时抛出,当前设置会在任意一个文件缺失时抛出两个异常。请问我做错了什么?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.xml.ws.Holder;

public class Inventory {

    static String FileSeparator = System.getProperty("file.separator");

    public static void main(String[] args) {
        String path = args[0];
        String name = args[1];
        ArrayList<Holder> because = new ArrayList<Holder>();

        try {
            File product = new File(path + name + ".pro");
            Scanner scan = new Scanner(product);
            while (scan.hasNext()) {
                System.out.print(scan.next());
            }
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println("Usage: java Inventory <path> <filename>");
            System.out.println("The products file \"" + name + ".pro\" does not exist.");
        }

        try {
            File command = new File(path + name + ".cmd");
            Scanner scan = new Scanner(command);

            while (scan.hasNext()) {
                System.out.println(scan.next());
            }
        } catch (FileNotFoundException f) {
            System.out.println("Usage: java Inventory <path> <filename>");
            System.out.println("The commands file \"" + name + ".cmd\" does not exist.");
        }

    }
}

1
可能是因为两者都缺失(或者你使用的路径在两种情况下都无效)? - assylias
看起来如果两者中任意一个或两个都缺失,就会触发它们两个,将 return; 添加到第一个可以使只缺失 .pro 文件的测试工作,但 .cmd 文件仍会触发两个异常。 - user2218030
2个回答

2

尝试像这样重构代码:

        File product = new File(path + name + ".pro");
        if (!product.exists()) {
            System.out.println("Usage: java Inventory <path> <filename>");
            System.out.println("The products file \"" + name + ".pro\" does not exist.");
            return;
        }

        File command = new File(path + name + ".cmd");
        if (!command.exists()) {
            System.out.println("Usage: java Inventory <path> <filename>");
            System.out.println("The commands file \"" + name + ".cmd\" does not exist.");
            return;
        }
        try {
            Scanner scan = new Scanner(product);
            while (scan.hasNext()) {
                System.out.print(scan.next());
            }
            scan.close();

            scan = new Scanner(command);
            while (scan.hasNext()) {
                System.out.println(scan.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

1

如果我将文件对象更改为以下内容,则对我有用:

File product = new File(path, name + ".pro");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接