如何解决Java commons cli 解析器无法识别命令行参数
这应该很简单,但我不确定为什么它不起作用。我正在尝试使用 apache commons CLI 库传递带有名称的参数(因此我可以按任何顺序传递参数),但它似乎不起作用。我想从 Eclipse IDE 传递参数。我知道这部分不是问题,因为我可以用 args[0] 类型打印参数。
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class MainClass {
public static void main(String[] args) throws ParseException {
System.out.println(args[0]);
Options options = new Options();
options.addOption("d",false,"add two numbers");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options,args);
if(cmd.hasOption("d")) {
System.out.println("found d");
} else {
System.out.println("Not found");
}
}
以上几行与网上给出的示例完全一样,但我不知道为什么它不起作用。我从一天开始就在为此苦苦挣扎。请帮助我哪里出错了。
解决方法
根据 examples 参数的名称应该出现在命令行中
没有价值的财产
Usage: ls [OPTION]... [FILE]...
-a,--all do not hide entries starting with .
相应的代码是:
// create the command line parser
CommandLineParser parser = new DefaultParser();
// create the Options
Options options = new Options();
options.addOption( "a","all",false,"do not hide entries starting with ." );
在这种情况下正确的调用是:
ls -a
或 ls --all
值用空格分隔
-logfile <file> use given file for log
各自的代码是:
Option logfile = OptionBuilder.withArgName( "file" )
.hasArg()
.withDescription( "use given file for log" )
.create( "logfile" );
调用将是:
app -logfile name.of.file.txt
值用等号分隔
-D<property>=<value> use value for given property
代码是:
Option property = OptionBuilder.withArgName( "property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription( "use value for given property" )
.create( "D" );
调用将是:
app -Dmyprop=myvalue
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。