日期:2014-05-16 浏览次数:20812 次
一旦你定义了类的参数,创建一个CommandLineParser,并分析已传送到主方法中的组。
package com.founder.common;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class OptionsTip {
?public static void main(String[] args) {
??try {
???Options opts = new Options();
???opts.addOption("h", false, "Print help for this application");
???opts.addOption("u", true, "The username to use");
???opts.addOption("dsn", true, "The data source to use");
???BasicParser parser = new BasicParser();
???CommandLine cl = parser.parse(opts, args);
???
???if (cl.hasOption('h')) {
????HelpFormatter hf = new HelpFormatter();
????hf.printHelp("OptionsTip", opts);
???} else {
????System.out.println(cl.getOptionValue("u"));
????System.out.println(cl.getOptionValue("dsn"));
???}
??} catch (ParseException pe) {
???pe.printStackTrace();
??}
?}
}
注:使用此程序时候别忘了把commons-cli-1.0.jar加入到你的classpath中
运行结果:
E:\javaworkspace\collection\src>java com.founder.common.OptionsTip -h
usage: OptionsTip
?-dsn??? The data source to use
?-h????? Print help for this application
?-u????? The username to use
E:\javaworkspace\collection\src>java com.founder.common.OptionsTip -u eric -dsn founder
eric
founder