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


当前回答

我一直试图维护一个Java CLI解析器列表。

航空公司 Active Fork: https://github.com/rvesse/airline argparse4j argparse args4j clajr cli-parser CmdLn 命令行 DocOpt.java 海豚getopt DPML CLI (Jakarta Commons CLI2分支) 马蒂亚斯·劳克斯博士 Jakarta Commons CLI jargo jargp jargs java-getopt jbock JCLAP jcmdline jcommander jcommando Jewelcli(作者:我) JOpt简单 jsap naturalcli Object Mentor CLI文章(关于重构和TDD的更多内容) parse-cmd ritopt 罗普 TE-Code命令 picocli有ANSI彩色使用帮助和自动完成

其他回答

看看Spring Shell

Spring Shell’s features include A simple, annotation driven, programming model to contribute custom commands Use of Spring Boot auto-configuration functionality as the basis for a command plugin strategy Tab completion, colorization, and script execution Customization of command prompt, shell history file name, handling of results and errors Dynamic enablement of commands based on domain specific criteria Integration with the bean validation API Already built-in commands, such as clear screen, gorgeous help, exit ASCII art Tables, with formatting, alignment, fancy borders, etc.

如果您已经在使用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方法将在上下文成功启动后被调用。

如果你需要在启动你的应用程序上下文之前访问参数,你可以简单地手动解析应用程序参数:

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

}

最后,如果您需要访问bean中的参数,只需注入ApplicationArguments:

@Component
public class MyBean {

   @Autowired
   private ApplicationArguments arguments;

   // ...
}

看看这些:

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

或者自己卷:

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


例如,这是你如何使用common -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 = null;//not a good practice, it serves it purpose 

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

    }

}

命令行用法:

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

看看Commons CLI项目,里面有很多好东西。

Argparse4j是我发现的最好的。它模仿Python的argparse库,非常方便和强大。