当前位置: 首页 > 工具软件 > JOpt Simple > 使用案例 >

JOpt Simple OptionParser解析命令参数

贡俊
2023-12-01

JOpt Simple可以用来解析命令参数,以Java为例

import joptsimple.OptionParser;
import joptsimple.OptionSet;
public class OptionParserTest {
public static void main(String[] args) throws Exception {
	OptionParser parser = new OptionParser();
	parser.accepts("zookeeper", "it is required").withRequiredArg().describedAs( "zookeeper connect address." ).ofType( String.class );
	OptionSet options = parser.parse(args);
	if(!options.has("zookeeper")) {
		throw new Exception("zookeeper is required");
	}
	System.out.println((String)options.valueOf("zookeeper"));
	}
}

代表的意思是,输入参数中必须包含“zookeeper”参数,否则会抛出异常;

验证:
1.将OptionParser导出为一个jar文件;
2.打开cmd命令窗口;
3.输入 java -jar OptionParserTest;
4.会提示"zookeeper is required";
5.重新输入:java -jar OptionParserTest --zookeeper localhost:2181
6.结果打印:localhost:2181

下面参考一下kafka的参数解析

//创建解析对象
val parser = new OptionParser(false)
//定义需要解析的参数
val zkConnectOpt = parser.accepts("zookeeper", "REQUIRED: The connection string for the zookeeper connection in the form host:port. " +
                                      "Multiple hosts can be given to allow fail-over.")
           .withRequiredArg
           .describedAs("hosts")
           .ofType(classOf[String])
//解析入口参数           
val options = parser.parse(args : _*)

//检查必须参数
CommandLineUtils.checkRequiredArgs(parser, options, zkConnectOpt)

//CommandLineUtils类的checkRequiredArgs方法如下
def checkRequiredArgs(parser: OptionParser, options: OptionSet, required: OptionSpec[_]*) {
    for (arg <- required) {
      if(!options.has(arg))
        printUsageAndDie(parser, "Missing required argument \"" + arg + "\"")
    }
}
 类似资料: