gpt4 book ai didi

Java Apache CLI 可选命令行参数不起作用

转载 作者:行者123 更新时间:2023-11-30 06:57:43 25 4
gpt4 key购买 nike

尝试使用 Apache Commons Command Line Interface 1.3.1 from here它适用于必需的参数,但似乎删除了任何可选参数。谁能发现我下面的代码有问题?

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class TestCommandLine {

public static void main(String[] args) {

// ***** test with command line arguments -R myfirstarg -O mysecondarg *****
// ***** the second arg is not being captured *****

System.out.println("Number of Arguments : " + args.length);

String commandline = "";
for (String arg : args) {
commandline = commandline + (arg + " ");
}
commandline.trim();
System.out.println("Command-line arguments: " + commandline);

// create Options object
Options options = new Options();
options.addOption("R", true, "Enter this required argument");
Option optionalargument = Option.builder("O")
.optionalArg(true) // if I change this line to .hasArg(true) it works, but then is not optional
.desc("Enter this argument if you want to")
.build();
options.addOption(optionalargument);

// initialize variables used with command line arguments
String firstargument = null;
String secondargument = null;


CommandLineParser parser = new DefaultParser();
try {
// parse the command line arguments
CommandLine cmd = parser.parse( options, args );

firstargument = cmd.getOptionValue("R");
secondargument = cmd.getOptionValue("O");

if(cmd.hasOption("R")){
if(firstargument == null){
System.out.println("Must provide the first argument ... exiting...");
System.exit(0);
}
else {
System.out.println("First argument is " + firstargument);
}
}
if(cmd.hasOption("O")) {
// optional argument
if (secondargument == null){
System.out.println("Second argument is NULL");
}
else{
// should end up here if optional argument is provided, but it doesn't happen
System.out.println("Second argument is " + secondargument);
}
}

}
catch( ParseException exp ) {
// oops, something went wrong
System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
}
}

}

以上代码的输出是:

Number of Arguments : 4
Command-line arguments: -R myfirstarg -O mysecondarg
First argument is myfirstarg
Second argument is NULL

为什么没有捕获“mysecondarg”?如果我将 .optionalArg(true) 行更改为 .hasArg(true),则捕获第二个参数,但整个想法是能够有选择地省略第二个参数。

最佳答案

除了 hasOptionalArgs 之外,您似乎还需要设置 numberOfArgs 才能使其正常工作。

关于Java Apache CLI 可选命令行参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33338787/

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