如何在Java中解析命令行参数? [英] How do I parse command line arguments in Java?

查看:234
本文介绍了如何在Java中解析命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中解析命令行参数的好方法是什么?

What is a good way of parsing command line arguments in Java?

推荐答案

最近的后起之秀是 picocli (ANSI颜色,命令行自动完成,注释和编程API等)。

A recent rising star is picocli (ANSI colors, command line autocompletion, both annotations and programmatic API, and more).

同时检查这些(旧):

  • http://commons.apache.org/cli/
  • http://www.martiansoftware.com/jsap/

或者自己动手:

  • http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

例如,这就是你使用 commons-cli 解析2个字符串参数:

For instance, this is how you use commons-cli to parse 2 string arguments:

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);

    }

}

来自命令的用法line:

usage from command line:

$> 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

这篇关于如何在Java中解析命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆