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

本文介绍如何使用Maven引入commons-cli依赖,并通过Java程序解析命令行参数,获取配置文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值