commons-cli的一些应用

CLI 即Command Line Interface,也就是"命令行接口",它为Java 程序访问和解析命令行
参数提供了一种统一的接口。

主要处理java启动时,输入命令行的
纯java编译完*.class以后,会通过,下面命令运行带main的类
java 类名
打成jar包的则通过下面命令(带main方法)
java –jar 包名.jar
在eclipse下运行则需要通过Run as /runConfigurations/Arguments来进行命令行参数配置

参数的配置和我们常用的命令一样,横杠+参数名+空格+参数值
-参数名 参数值
然后java会根据main方法中 String[] args来取得命令行参数

通过使用commons-cli则可以很容易的访问参数,而不必去循环String[] args


TestCliDemo.java代码:
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public class TestCliDemo {

	/**
	 * @param args
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
		Options options = new Options();   
        options.addOption("t", false, "display current time");//参数不可用   
        options.addOption("c", true, "country code");//参数可用   
  
        CommandLineParser parser = new PosixParser();   
        CommandLine cmd = parser.parse(options, args);   
  
        if (cmd.hasOption("c")) {   
            String countryCode = cmd.getOptionValue("c");   
            System.out.println(countryCode);   
        }   
  
        if (cmd.hasOption("t")) {   
            String countryCode = cmd.getOptionValue("t");   
            System.out.println(countryCode);   
        }
	}

}


在MyEclipse中运行此类,在工程树中右键单击该类选择 Run As --> Ru n Configurations ... --> 选择第二个面板[(x)=Arguments] --> 在Program arguments: 中输入-c code -t time


运行结果: 
code 
null

猜你喜欢

转载自shihuan830619.iteye.com/blog/1160238