一、简介
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
很多时候我们想自己维护命令行操作,常常考虑不全面,而且也是在重复发明轮子,commons-cli 为我们提供了完整的命令行全套解决方案,下面就用heritri3里面使用commons-cli的例子来介绍这个工具的使用。
第一步:我们需要设置我们的命令
private static Options options() {
Options options = new Options();
options.addOption("h", "help", true, "Usage information." );
options.addOption("a", "web-admin", true, "REQUIRED. Specifies the " +
"authorization username and password which must be supplied to " +
"access the web interface. This may be of the form " +
"\"password\" (which leaves username as the default 'admin'), " +
"\"username:password\", or \"@filename\" for a file that " +
"includes the single line \"username:password\". ");
options.addOption("j", "jobs-dir", true, "The jobs directory. " +
"Defaults to ./jobs");
options.addOption("l", "logging-properties", true,
"The full path to the logging properties file " +
"(eg, conf/logging.properties). If present, this file " +
"will be used to configure Java logging. Defaults to " +
"${heritrix.home}/conf/logging.properties or if no " +
"heritrix.home property set, ./conf/logging.properties");
options.addOption("b", "web-bind-hosts", true,
"A comma-separated list of addresses/hostnames for the " +
"web interface to bind to.");
options.addOption("p", "web-port", true, "The port the web interface " +
"should listen on.");
options.addOption("s", "ssl-params", true, "Specify a keystore " +
"path, keystore password, and key password for HTTPS use. " +
"Separate with commas, no whitespace.");
return options;
}
private static CommandLine getCommandLine(PrintStream out, String[] args) {
CommandLineParser clp = new GnuParser();
CommandLine cl;
try {
cl = clp.parse(options(), args);
} catch (ParseException e) {
usage(out, args);
return null;
}
if (cl.getArgList().size() != 0) {
usage(out, args);
return null;
}
return cl;
}
CommandLine cl = getCommandLine(startupOut, args);
CommandLine cl = getCommandLine(startupOut, args);
if (cl == null) return;
if (cl.hasOption('h')) {
usage(startupOut, args);
return ;
}