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.");
        }

    }
}
4

2 回答 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();
        }
于 2013-03-28T01:47:21.910 回答
1

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

File product = new File(path, name + ".pro");
于 2013-03-28T01:53:32.247 回答