2011-01-14 9 views
20

Apache Commons CLIを使用してJavaのコマンドライン引数を処理しています。Apache Commons CLIライブラリの使用時にパラメータを取得する方法

私はabオプションを宣言しました。私はCommandLine.getOptionValue()を使用して値にアクセスできます。

Usage: myapp [OPTION] [DIRECTORY] 

Options: 
-a  Option A 
-b  Option B 

DIRECTORY変数を宣言してアクセスするにはどうすればよいですか?オプションが処理された後に残っているものは何でも返し

CommandLine.getArgList() 

+0

? –

答えて

29

は、以下の方法を使用します。

+0

すべてのオプションの引数の数が無制限の場合はどうなりますか? – Zangdak

6

別のオプション(-d)を使用して、ユーザーにとってより直感的なディレクトリを識別することをお勧めします。

または、次のコードは、残りの引数リスト

を取得実証
public static void main(final String[] args) { 
    final CommandLineParser parser = new BasicParser(); 
    final Options options = new Options(); 
    options.addOption("a", "opta", true, "Option A"); 
    options.addOption("b", "optb", true, "Option B"); 

    final CommandLine commandLine = parser.parse(options, args); 

    final String optionA = getOption('a', commandLine); 
    final String optionB = getOption('b', commandLine); 

    final String[] remainingArguments = commandLine.getArgs(); 

    System.out.println(String.format("OptionA: %s, OptionB: %s", optionA, optionB)); 
    System.out.println("Remaining arguments: " + Arrays.toString(remainingArguments)); 
} 

public static String getOption(final char option, final CommandLine commandLine) { 

    if (commandLine.hasOption(option)) { 
     return commandLine.getOptionValue(option); 
    } 

    return StringUtils.EMPTY; 
} 
あなたは `HelpFormatter`印刷` [OPTION] [DIRECTORY] `を行いましたか
+1

これは、HelpFormatterが[DIRECTORY]引数を印刷するために使用されることを追加したいと思います。 'HelpFormatter formatter = new HelpFormatter();' 'formatter.printHelp(" myapp [OPTION] [DIRECTORY]オプション); ' – Blazes

関連する問題