JAVA 命令行参数解析,org.apache.commons.cli的使用

  • maven依赖引入
<dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.2</version>
</dependency>
  • 示例代码,以下是从命令行读取文件路径的例子
private static void main(String[] args) {
        
        final Options options = new Options();
        final Option option = new Option("f", true, "Configuration file path");
        options.addOption(option);
        
        final CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (final ParseException e) {
            throw new Exception("parser command line error",e);
        }
        
        String configFilePath = null;
        if (cmd.hasOption("f")) {
            configFilePath = cmd.getOptionValue("f");
        }else{
            System.err.println("please input the configuration file path by -f option");
            System.exit(1);
        }
        if (StringUtils.isBlank(configFilePath)) {
            throw new Exception("Blank file path");
        }
        
        return configFilePath;
    }
原文地址:https://www.cnblogs.com/fightingcoding/p/6396165.html