2014-03-29 28 views
0

我需要我的代码读取文件路径并在文件末尾分析文件,并根据指定,如果没有给出有效的路径,它必须退出。当我输入“java ClassName pathway/file”之类的东西时,它只是接受更多的输入。如果我把它放在完全相同的路径上,它就会按照我想要的那样做,但它需要以前者的格式来完成。我应该不使用扫描仪吗? (TextFileAnalyzer是另一个类我写的确实的文件分析,很明显)的命令行上指定putty命令行参数与java怪异地行动

import java.util.Scanner; 

public class Assignment8 { 

    public static void main(String[] args) { 
     Scanner stdin = new Scanner(System.in); 
     String path = null; 
     TextFileAnalyzer analysis = null; 
     if (args.length == 0 || java.lang.Character.isWhitespace(args[0].charAt(0))) 
      System.exit(1); 
     try { 
      path = stdin.next(); 
      analysis = new TextFileAnalyzer(path); 
     } catch (Exception e) { 
      System.err.println(path + ": No such file or directory"); 
      System.exit(2); 
     } 
     System.out.println(analysis); 
     stdin.close(); 
     System.exit(0); 

    } 
} 
+0

当你说它需要以“以前的格式”来做时,你是说输入必须看起来像'java ClassName filepath/file',然后你将从该输入中解析出文件路径/ file'? – leigero

+0

是的。它似乎认识到'文件路径/文件'部分是因为没有它,它只是退出,根据if语句,但它没有真的做任何事情,直到我再次输入它 – user3475026

回答

3

参数是不一样的通过标准输入在控制台输入的信息。从System.in读取将允许您读取输入,并且这与命令行参数无关。

您当前的非工作代码的问题在于,当您检查是否指定了参数时,您实际上并没有使用args[0]作为路径名,而只是继续阅读用户输入。

命令行参数通过参数String[]传递给main。在你的情况下,它的第一个参数,所以它会在args[0]

public static void main (String[] args) { 
    String pathname; 
    if (args.length > 0) { 
     pathname = args[0]; // from the command line 
    } else { 
     // get pathname from somewhere else, e.g. read from System.in 
    } 
} 

,或者更严格:

public static void main (String[] args) { 
    String pathname; 
    if (args.length > 1) { 
     System.err.println("Error: Too many command line parameters."); 
     System.exit(1); 
    } else if (args.length > 0) { 
     pathname = args[0]; // from the command line 
    } else { 
     // get pathname from somewhere else, e.g. read from System.in 
    } 
} 

退房的official tutorial on command-line arguments以获取更多信息。


顺便说一句,我注意到你有这个在您的if条件:

java.lang.Character.isWhitespace(args[0].charAt(0)) 

,开头和结尾的空白将被自动剪切掉不带引号的命令行参数,所以,将永远是false,除非用户明确地使用引号和不一样的东西:

java ClassName " something" 

即使在这种情况下,你可能只想接受它的d使用args[0].trim()更宽松。

+1

ahhhhhhh是这完美地工作谢谢你很多(这项任务是在一个小时内完成的)。 – user3475026