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
package com.geo.gdata.gstream.core.topology;
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;
/*
输入参数 -c c -t t
运行结果:
c
t
*/
public class Test {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("t", true, "country code t"); //参数可用
options.addOption("c", true, "country code c"); //参数可用
options.addOption("f", false, "display current time"); //参数不可用
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);
}
}
}