JAVA 命令行:输入两个字长的命令时"file not found exception"?(当我输入一个单词命令时,它工作正常。



我的代码旨在为我在 Mac 命令行上键入的命令提供 1) 简单和 2) 详细的类型答案,具体取决于我输入的命令(我想通过我输入的单词数来区分,但是,命令行只执行一个单词长的命令,并抛出两个单词长的命令的异常)。

当我输入java <filename> <input>时,我希望它产生一个简单的版本,这是我编程的,当我输入java <filename> --verbose <input>时,我希望它产生一个详细的版本,我也编程了。

简单版本工作正常,但详细版本抛出错误,指示错误涉及扫描程序。这是代码片段(仅供参考。这是命令行输出。

public class Test {
public static Scanner scan;
public static void main(String args[]) {
//To check the length of args --> I take "check" array as an input for my method "eachCycleFCFS".
for (int a = 0; a < args.length; a++) {
check.add(args[a]);
}
try {
String fileAddress = args[0];
File fileInput  = new File(fileAddress); //Read
scan = new Scanner(fileInput);
int numProcesses  = scan.nextInt();
...
for (int m = 0; m < numProcesses; m++) {
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int io = scan.nextInt();
...
}
}   
catch (Exception e){
e.printStackTrace();
System.out.printf(" Error: File not foundd. n");
}
}
public static void eachCycleFCFS (Queue<Process> processes, int numProcesses, Process[] allProcesses, Process[] original, Process[] realOriginal, ArrayList<String> check) {                
File fileInput = new File("random-numbers.txt");
Scanner randomInput = null;
try {
randomInput = new Scanner(fileInput);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (check.size() == 2) {
if (check.get(0).contains("verbose")) {
//Produce the detailed output
}
}
else {
//Produce the simple output
}
while (terminatedProcesses != numProcesses) {
if (check.size() == 2) {
if (check.get(0).equals("--verbose")) {
//Produce the detailed output
}
}
}
}

}

对于一个字长的命令,代码应生成我编程的简单输出。对于两个字长的命令,代码应在简单输出之上再生成一个信息块。 简单版本很好。 详细版本是这样说的:

blahblahblah$ java Scheduling2 --verbose input-1.txt
java.io.FileNotFoundException: --verbose (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Scheduling2.main(Scheduling2.java:18)
Error: File not found.

感谢您的帮助,如果我可以添加更多信息以使您更轻松,请告诉我,请:)!

问题是你总是从你的第一个参数中获取文件名:

String fileAddress = args[0];
File fileInput  = new File(fileAddress); //Read

但在这种情况下,您的第一个论点(例如args[0]) 是"--冗长"。所以new File("--verbose")FileNotFoundException失败了,因为文件"--verbose"确实在当前目录中不存在。

你可能想做的是跳过以--开头的参数,例如

int argNum = 0;
while(argNum<args.length && args[argNum].startsWith("--")) {
argNum++;
}
if(!(argNum < args.length)) {
throw new IllegalArgumentException("Please pass file path in parameters");
}
String fileAddress = args[argNum];
File fileInput  = new File(fileAddress); //Read

相关内容

最新更新