実行時引数を操作(Apache Commons CLI)

実行時引数を解析する。

public static void main(String[] args) {
	Options options = new Options();
	options.addOption("h", "help", false, "ヘルプを表示する。");
	options.addOption("a", "aaa", false, "引数なしオプションです。");
	options.addOption("b", "bbb", true, "引数ありオプションです。");

	// パーサー生成
	// Apache Commons CLI 1.2では、BasicParserを使用していたが、
	// 1.3では、DefaultParserを使用する。
	DefaultParser parser = new DefaultParser();

	try {
		CommandLine cl = parser.parse(options, args);

		if (cl.hasOption("h")) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("command_name [options] <infile>", options);
		} else {
			System.out.println("オプションa : " + cl.hasOption("a"));
			System.out.println("オプションb : " + cl.getOptionValue("b"));
			System.out.println("必須引数 : " + cl.getArgs()[0]);
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
}