lin*_*lof 547 java command-line command-line-arguments picocli
在Java中解析命令行参数的好方法是什么?
Vin*_*vic 372
最近的一颗新星是picocli(ANSI颜色,命令行自动完成,注释和编程API等等).
还要检查这些(较旧):
或滚动你自己:
例如,这是你commons-cli用来解析2个字符串参数的方法:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
}
String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");
System.out.println(inputFilePath);
System.out.println(outputFilePath);
}
}
Run Code Online (Sandbox Code Playgroud)
从命令行使用:
$> java -jar target/my-utility.jar -i asd
Missing required option: o
usage: utility-name
-i,--input <arg> input file path
-o,--output <arg> output file
Run Code Online (Sandbox Code Playgroud)
Ced*_*ust 302
看一下最近的JCommander.
我创造了它.我很高兴收到问题或功能要求.
lex*_*ope 226
我一直在尝试维护一个Java CLI解析器列表.
Rem*_*pma 19
购买还是建造?
许多类似实用程序的小应用程序可能会使用自己的命令行解析来避免额外的外部依赖.
picocli可能很有趣.它被设计为作为源的一个更简单的替代方法,将阴影罐放入uberjar中.
您可能喜欢的另一个功能是它的彩色使用帮助.
解析器功能:
<command> -xvfInputFile以及<command> -x -v -f InputFile)"1..*","3..5"使用帮助消息很容易使用注释进行自定义(无需编程).例如:
(来源)
我无法抗拒添加一个屏幕截图来显示可能的用法帮助消息.使用帮助是您的应用程序的面貌,所以要有创意,玩得开心!
免责声明:我创建了picocli.反馈或问题非常欢迎.
Joh*_*las 11
我知道这里的大多数人会找到 1000 万个不喜欢我的方式的理由,但没关系。我喜欢保持简单,所以我只是使用 '=' 将键与值分开,并将它们存储在 HashMap 中,如下所示:
Map<String, String> argsMap = new HashMap<>();
for (String arg: args) {
String[] parts = arg.split("=");
argsMap.put(parts[0], parts[1]);
}
Run Code Online (Sandbox Code Playgroud)
您可以始终维护一个包含您期望的参数的列表,以帮助用户以防他忘记参数或使用错误的参数......但是,如果您想要太多功能,这个解决方案无论如何都不适合您。
这是Google的命令行解析库,作为Bazel项目的一部分开源.我个人认为它是最好的,比Apache CLI容易得多.
https://github.com/pcj/google-options
maven_jar(
name = "com_github_pcj_google_options",
artifact = "com.github.pcj:google-options:jar:1.0.0",
sha1 = "85d54fe6771e5ff0d54827b0a3315c3e12fdd0c7",
)
Run Code Online (Sandbox Code Playgroud)
dependencies {
compile 'com.github.pcj:google-options:1.0.0'
}
Run Code Online (Sandbox Code Playgroud)
<dependency>
<groupId>com.github.pcj</groupId>
<artifactId>google-options</artifactId>
<version>1.0.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
创建一个扩展OptionsBase和定义您的类的类@Option.
package example;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import java.util.List;
/**
* Command-line options definition for example server.
*/
public class ServerOptions extends OptionsBase {
@Option(
name = "help",
abbrev = 'h',
help = "Prints usage info.",
defaultValue = "true"
)
public boolean help;
@Option(
name = "host",
abbrev = 'o',
help = "The server host.",
category = "startup",
defaultValue = ""
)
public String host;
@Option(
name = "port",
abbrev = 'p',
help = "The server port.",
category = "startup",
defaultValue = "8080"
)
public int port;
@Option(
name = "dir",
abbrev = 'd',
help = "Name of directory to serve static files.",
category = "startup",
allowMultiple = true,
defaultValue = ""
)
public List<String> dirs;
}
Run Code Online (Sandbox Code Playgroud)
解析参数并使用它们.
package example;
import com.google.devtools.common.options.OptionsParser;
import java.util.Collections;
public class Server {
public static void main(String[] args) {
OptionsParser parser = OptionsParser.newOptionsParser(ServerOptions.class);
parser.parseAndExitUponError(args);
ServerOptions options = parser.getOptions(ServerOptions.class);
if (options.host.isEmpty() || options.port < 0 || options.dirs.isEmpty()) {
printUsage(parser);
return;
}
System.out.format("Starting server at %s:%d...\n", options.host, options.port);
for (String dirname : options.dirs) {
System.out.format("\\--> Serving static files at <%s>\n", dirname);
}
}
private static void printUsage(OptionsParser parser) {
System.out.println("Usage: java -jar server.jar OPTIONS");
System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),
OptionsParser.HelpVerbosity.LONG));
}
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/pcj/google-options
也许这些
用于Java的JArgs命令行选项解析套件 - 这个小项目提供了一个方便,紧凑,预打包和全面记录的命令行选项解析器套件,供Java程序员使用.最初,提供了与GNU风格的'getopt'兼容的解析.
ritopt,Java的终极选项解析器 - 虽然已经提出了几个命令行选项标准,但ritopt遵循opt包中规定的约定.
如果您已经在使用 Spring Boot,则参数解析是开箱即用的。
如果你想在启动后运行一些东西,实现ApplicationRunner接口:
@SpringBootApplication
public class Application implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(ApplicationArguments args) {
args.containsOption("my-flag-option"); // test if --my-flag-option was set
args.getOptionValues("my-option"); // returns values of --my-option=value1 --my-option=value2
args.getOptionNames(); // returns a list of all available options
// do something with your args
}
}
Run Code Online (Sandbox Code Playgroud)
您的run方法将在上下文成功启动后被调用。
如果您需要在启动应用程序上下文之前访问参数,您只需手动解析应用程序参数:
@SpringBootApplication
public class Application implements ApplicationRunner {
public static void main(String[] args) {
ApplicationArguments arguments = new DefaultApplicationArguments(args);
// do whatever you like with your arguments
// see above ...
SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,如果您需要访问 bean 中的参数,只需注入ApplicationArguments:
@Component
public class MyBean {
@Autowired
private ApplicationArguments arguments;
// ...
}
Run Code Online (Sandbox Code Playgroud)
你可能会发现这篇不幸的元文章作为一个有趣的起点:
http://furiouspurpose.blogspot.com/2008/07/command-line-parsing-libraries-for-java.html
| 归档时间: |
|
| 查看次数: |
342370 次 |
| 最近记录: |