cli - downgoon/hello-world GitHub Wiki

cli

目标样例

Parsing failed.  Reason: Unrecognized option: -a
usage: ant [-buildfile <file>] [-D <property=value>] [-debug] [-emacs]
       [-find <file>] [-help] [-listener <classname>] [-logfile <file>]
       [-logger <classname>] [-projecthelp] [-quiet] [-verbose] [-version]
 -buildfile <file>       use given buildfile
 -D <property=value>     use value for given property
 -debug                  print debugging information
 -emacs                  produce logging information without adornments
 -find <file>            search for buildfile towards the root of the
                         filesystem and use it
 -help                   print this message
 -listener <classname>   add an instance of class as a project listener
 -logfile <file>         use given file for log
 -logger <classname>     the class which it to perform logging
 -projecthelp            print project help information
 -quiet                  be extra quiet
 -verbose                be extra verbose
 -version                print the version information and exit

  • 从是否带参数角度:选项区分功能/开关选项(Boolean Options)和带参选项(Argument Options)。默认是前者。比如:tar -zxvf foo.tar.gz,里面的-zxvf都表示一个功能,并不需要给出取值;再如:curl -x 10.10.1.186:8080 https://www.baidu.com,里面的-x就是带参选项

  • 是否必选的角度:区分必选可选。默认是可选。如果要必选,可以:new Option("f", "file").setRequired(true);

样例代码

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public class AntCli {

	@SuppressWarnings({ "static-access" })
	public static void main(String[] args) throws Exception {

		args = argsArray("ant -a b");

		// Boolean Options

		// -help print this message
		// -projecthelp print project help information
		// -version print the version information and exit
		// -quiet be extra quiet
		// -verbose be extra verbose
		// -debug print debugging information
		// -emacs produce logging information without adornments

		Option help = new Option("help", "print this message");
		Option projecthelp = new Option("projecthelp", "print project help information");
		Option version = new Option("version", "print the version information and exit");
		Option quiet = new Option("quiet", "be extra quiet");
		Option verbose = new Option("verbose", "be extra verbose");
		Option debug = new Option("debug", "print debugging information");
		Option emacs = new Option("emacs", "produce logging information without adornments");

		// Argument Options
		// The argument options are created using the OptionBuilder.

		// -logfile <file> use given file for log
		// -logger <classname> the class which is to perform logging
		// -listener <classname> add an instance of class as a project listener
		// -buildfile <file> use given buildfile
		// -find <file> search for buildfile towards the root of the
		// filesystem and use it

		// The next Option created will require an argument value.
		Option logfile = OptionBuilder.withArgName("file").hasArg().withDescription("use given file for log")
				.create("logfile");

		Option logger = OptionBuilder.withArgName("classname").hasArg()
				.withDescription("the class which it to perform " + "logging").create("logger");

		Option listener = OptionBuilder.withArgName("classname").hasArg()
				.withDescription("add an instance of class as " + "a project listener").create("listener");

		Option buildfile = OptionBuilder.withArgName("file").hasArg().withDescription("use given buildfile")
				.create("buildfile");

		Option find = OptionBuilder.withArgName("file").hasArg()
				.withDescription("search for buildfile towards the " + "root of the filesystem and use it")
				.create("find");

		// Java Property Option
		// -D<property>=<value> use value for given property

		// The map of properties specified by this option can later be retrieved
		// by calling getOptionProperties("D") on the CommandLine.
		Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
				.withDescription("use value for given property").create("D");

		// hasArgs(2).withValueSeparator(): A2 args with separator

		// Create the Options
		Options options = new Options();

		options.addOption(help);
		options.addOption(projecthelp);
		options.addOption(version);
		options.addOption(quiet);
		options.addOption(verbose);
		options.addOption(debug);
		options.addOption(emacs);
		options.addOption(logfile);
		options.addOption(logger);
		options.addOption(listener);
		options.addOption(buildfile);
		options.addOption(find);
		options.addOption(property);

		// create the parser
		CommandLineParser parser = new PosixParser();
		CommandLine cmdLine = null;
		try {
			// parse the command line arguments
			cmdLine = parser.parse(options, args);

		} catch (ParseException exp) {
			// oops, something went wrong
			System.err.println("Parsing failed.  Reason: " + exp.getMessage());
			usage(options);
			System.exit(-1);
		}

		// Querying the commandline
		// has the buildfile argument been passed?
		if (cmdLine.hasOption("buildfile")) {
			// initialise the member variable
			String buildfileValue = cmdLine.getOptionValue("buildfile");
			System.out.println("buildfile: " + buildfileValue);
		}

	}

	private static void usage(Options options) {
		// automatically generate the help statement
		HelpFormatter helpFormatter = new HelpFormatter();

		// true: generate a usage statment as well as the help information.
		helpFormatter.printHelp("ant", options, true);

	}

	private static String[] argsArray(String line) {
		List<String> tokens = new ArrayList<String>();
		StringTokenizer tokenizer = new StringTokenizer(line);
		while (tokenizer.hasMoreTokens()) {
			tokens.add(tokenizer.nextToken());
		}
		String[] itmes = new String[tokens.size()];
		tokens.toArray(itmes);
		return itmes;
	}

}

依赖的jar是:

<dependency>
			<groupId>commons-cli</groupId>
			<artifactId>commons-cli</artifactId>
			<version>1.2</version>
</dependency>

参考资料

⚠️ **GitHub.com Fallback** ⚠️