gpt4 book ai didi

java - Commons CLI 不支持我的命令行设置

转载 作者:行者123 更新时间:2023-11-29 05:06:48 24 4
gpt4 key购买 nike

使用 Apache Commons CLI 1.2这里。我有一个可执行 JAR,需要采用 2 个运行时选项,fizzbuzz;两者都是需要参数/值的字符串。我希望(如果可能的话)我的应用程序像这样执行:

java -jar myapp.jar -fizz "Alrighty, then!" -buzz "Take care now, bye bye then!"

在这种情况下,fizz 选项的值将是“Alrighty, then!”等。

这是我的代码:

public class MyApp {
private Options cmdLineOpts = new Options();
private CommandLineParser cmdLineParser = new GnuParser();
private HelpFormatter helpFormatter = new HelpFormatter();

public static void main(String[] args) {
MyApp myapp = new MyApp();
myapp.processArgs(args);
}

private void processArgs(String[] args) {
Option fizzOpt = OptionBuilder
.withArgName("fizz")
.withLongOpt("fizz")
.hasArg()
.withDescription("The fizz argument.")
.create("fizz");

Option buzzOpt = OptionBuilder
.withArgName("buzz")
.withLongOpt("buzz")
.hasArg()
.withDescription("The buzz argument.")
.create("buzz");

cmdLineOpts.addOption(fizzOpt);
cmdLineOpts.addOption(buzzOpt);

CommandLine cmdLine;

try {
cmdLine = cmdLineParser.parse(cmdLineOpts, args);

// Expecting to get a value of "Alright, then!"
String fizz = cmdLine.getOptionValue("fizz");
System.out.println("Fizz is: " + fizz);
} catch(ParseException parseExc) {
helpFormatter.printHelp("myapp", cmdLineOpts, true);
throw parseExc;
}
}
}

当我运行它时,我得到以下输出:

Fizz is: null

我需要对我的代码做些什么,才能按我希望的方式调用我的应用程序?或者我最接近它的是什么?

加分项:如果有人能向我解释OptionBuilderwithArgName(...)之间的区别withLongOpt(...)create(...) 参数,因为我为它们传递了相同的值,就像这样:

Option fizzOpt = OptionBuilder
.withArgName("fizz")
.withLongOpt("fizz") } Why do I have to pass the same value in 3 times to make this work?!?
.create("fizz");

最佳答案

首先是 .hasArg()在您的 OptionBuilder 上告诉它您希望在参数标志之后有一个参数。

我让它在这个命令行下工作

--fizz "VicFizz is good for you" -b "VicBuzz is also good for you"

使用下面的代码——我把它放在构造函数中

Option fizzOpt = OptionBuilder
.withArgName("Fizz")
.withLongOpt("fizz")
.hasArg()
.withDescription("The Fizz Option")
.create("f");

cmdLineOpts.addOption(fizzOpt);
cmdLineOpts.addOption("b", true, "The Buzz Option");

分割

选项设置是必要的,以便在命令行上提供更多的可用性,以及一个很好的使用消息(见下文)

  • .withArgName("Fizz") : 在用法中给你的论点一个漂亮的标题(见下文)
  • .withLongOpt("fizz") : 允许--fizz "VicFizz is good for you"
  • .create("f") : 是主要参数并允许命令行 -f "VicFizz is good for you"
  • 请注意选项 bfuzz 的构造要简单得多,但会牺牲可读性用法

使用信息

就我个人而言,我喜欢打印出很好用法的 CLI 程序。您可以使用 HelpFormatter 执行此操作.例如:

private void processArgs(String[] args) {
if (args == null || args.length == ) {
helpFormatter.printHelp("Don't you know how to call the Fizz", cmdLineOpts);
...

这会打印一些有用的东西,比如:

usage: Don't you know how to call the Fizz
-b <arg> The Buzz Option
-f,--fizz <Fizz> The Fizz Option

请注意短选项 -f 的作用, 多头选项 --fizz , 和一个名字 <Fizz>显示,连同描述。

希望对你有帮助

关于java - Commons CLI 不支持我的命令行设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com