gpt4 book ai didi

Java Cli CommandLineParser

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:43 25 4
gpt4 key购买 nike

我正在尝试使用 Java cli commanlineparser 来解析以下参数,

java -OC:\mydirectory -NMyfile

选项-O 是目录,-N 是文件名。

我一直在网上寻找,但找不到一个很好的例子,这就是我想要做的,

Option option = new Option()
option.addOpton("O",true, "output directory)
option.addOpton("N",true, "file name)
...
CommandLineParser parser = new BasicParser();
...
if (cmd.hasOption("O")
...

基本上,我正在尝试添加多个选项并能够解析它们。这是使用上述选项运行程序的正确方法吗?

谢谢。

最佳答案

尝试以下操作:

...
Option opt1 = OptionBuilder.hasArgs(1).withArgName("output directory")
.withDescription("This is the output directory").isRequired(true)
.withLongOpt("output").create("O");

Option opt2 = OptionBuilder.hasArgs(1).withArgName("file name")
.withDescription("This is the file name").isRequired(true)
.withLongOpt("name").create("N")

Options o = new Options();
o.addOption(opt1);
o.addOption(opt2);
CommandLineParser parser = new BasicParser();

try {
CommandLine line = parser.parse(o, args); // args are the arguments passed to the the application via the main method
if (line.hasOption("output") {
//do something
} else if(line.hasOption("name") {
// do something else
}
} catch(Exception e) {
e.printStackTrace();
}
...

此外,您应该在命令行中的参数和值之间留一个空格。

关于Java Cli CommandLineParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11704338/

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