我需要两个单独的异常,如果缺少.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.");
}
}
}
答案 0 :(得分: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 :(得分:1)
如果我将File对象更改为以下内容,则适用于我:
File product = new File(path, name + ".pro");