Common CLI を使用して単純な引数を解析しようとしましたが、ParseException を受け取りました。
これが私のコードです:
@SuppressWarnings("static-access")
public class CmdParsingTest {
private static final Options options;
static {
options = new Options();
options.addOption(OptionBuilder.withLongOpt("schema-file")
.withDescription("path to schema file")
.hasArg()
.withArgName("schemaFile")
.create("source"));
options.addOption( OptionBuilder.withLongOpt("state-url")
.withDescription("state url")
.hasArg()
.withArgName("stateUrl")
.create("url"));
options.addOption( OptionBuilder.withLongOpt("update-number")
.withDescription("update number to start from")
.hasArg()
.withArgName("updateNum")
.create("update"));
options.addOption(OptionBuilder.withLongOpt("result-file")
.withDescription("use given file to save result")
.hasArg()
.withArgName("resultFile")
.create("result"));
}
public static void main(String[] args) {
args = new String[]{
"-source /home/file/myfile.txt",
"-url http://localhost/state",
"-result result.txt"};
// create the parser
CommandLineParser parser = new BasicParser();
try {
// parse the command line arguments
CommandLine cmd = parser.parse(options, args);
//other cool code...
}
catch( ParseException exp ) {
System.err.println( "Parsing of command line args failed. Reason: " + exp.getMessage() );
}
}
}
結果は次のとおりです。
コマンド ライン引数の解析に失敗しました。理由: 認識できないオプション: -source /home/file/myfile.txt
ダッシュなしで args を使用すると、例外はスローされず、cmd.hasOption("source")
false が返されます。
PS> 使用例では の使用DefaultParser
が推奨されていますが、CLI 1.3 でのみ表示されます (1.3 JavaDoc によると)。