2012-07-28 1 views
3
나는 follwing을 인수를 구문 분석 자바 CLI의 commanlineparser를 사용하는 것을 시도하고있다

,자바 CLI CommandLineParser

java -OC:\mydirectory -NMyfile 

옵션 -O는 디렉토리이며, -N은 파일의 이름입니다.

내가 온라인으로 찾고 있지만 좋은 예를 찾을 수 couldnt는 이것이 내가 뭘하려고 오전입니다되었습니다

Option option = new Option() 
option.addOpton("O",true, "output directory) 
option.addOpton("N",true, "file name) 
... 
CommandLineParser parser = new BasicParser(); 
... 
if (cmd.hasOption("O") 
... 

기본적으로, 여러 옵션을 추가하고 구문 분석 할 수 있도록 노력하고 있습니다. 위의 옵션으로 프로그램을 실행하는 올바른 방법입니까?

감사합니다.

+0

시도해 보셨습니까? 문제가 있습니까? apache commons cli 라이브러리를 사용하고 계시거나 직접 구현하려고하십니까? – peshkira

+0

예, 저는 apache cli를 사용하고 있습니다. "UnreconginziedOptionExcepton"이 표시됩니다. – Tony

답변

1

는 다음과 같은 시도 :

... 
Option opt1 = OptionBuilder.hasArgs(1).withArgName("output directory") 
    .withDescription("This is the output directory").isRequired(true) 
    .withLongOpt("output").create("O"); 

Option opt2 = OptionBuilder.hasArgs(1).withArgName("file name") 
    .withDescription("This is the file name").isRequired(true) 
    .withLongOpt("name").create("N") 

Options o = new Options(); 
o.addOption(opt1); 
o.addOption(opt2); 
CommandLineParser parser = new BasicParser(); 

try { 
    CommandLine line = parser.parse(o, args); // args are the arguments passed to the the application via the main method 
    if (line.hasOption("output") { 
    //do something 
    } else if(line.hasOption("name") { 
    // do something else 
    } 
} catch(Exception e) { 
    e.printStackTrace(); 
} 
... 

또한, 인수 및 명령 줄의 값 사이에 빈 공간을 남겨 두어야합니다.