How do I parse command line arguments in Java?

前端 未结 19 1656
终归单人心
终归单人心 2020-11-22 00:16

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

相关标签:
19条回答
  • 2020-11-22 00:38

    Take a look at the more recent JCommander.

    I created it. I’m happy to receive questions or feature requests.

    0 讨论(0)
  • 2020-11-22 00:41

    I wrote another one: http://argparse4j.sourceforge.net/

    Argparse4j is a command line argument parser library for Java, based on Python's argparse.

    0 讨论(0)
  • 2020-11-22 00:42

    Check these out:

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

    Or roll your own:

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

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

    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
    
    0 讨论(0)
  • 2020-11-22 00:43

    It is 2020, time to do better than Commons CLI... :-)

    Should you build your own Java command line parser, or use a library?

    Many small utility-like applications probably roll their own command line parsing to avoid the additional external dependency. picocli may be an interesting alternative.

    Picocli is a modern library and framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It lives in 1 source file so apps can include it as source to avoid adding a dependency.

    It supports colors, autocompletion, subcommands, and more. Written in Java, usable from Groovy, Kotlin, Scala, etc.

    Features:

    • Annotation based: declarative, avoids duplication and expresses programmer intent
    • Convenient: parse user input and run your business logic with one line of code
    • Strongly typed everything - command line options as well as positional parameters
    • POSIX clustered short options (<command> -xvfInputFile as well as <command> -x -v -f InputFile)
    • Fine-grained control: an arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*", "3..5"
    • Subcommands (can be nested to arbitrary depth)
    • Feature-rich: composable arg groups, splitting quoted args, repeatable subcommands, and many more
    • User-friendly: usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user
    • Distribute your app as a GraalVM native image
    • Works with Java 5 and higher
    • Extensive and meticulous documentation

    The usage help message is easy to customize with annotations (without programming). For example:

    (source)

    I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

    Disclaimer: I created picocli. Feedback or questions very welcome.

    0 讨论(0)
  • 2020-11-22 00:44

    Maybe these

    • JArgs command line option parsing suite for Java - this tiny project provides a convenient, compact, pre-packaged and comprehensively documented suite of command line option parsers for the use of Java programmers. Initially, parsing compatible with GNU-style 'getopt' is provided.

    • ritopt, The Ultimate Options Parser for Java - Although, several command line option standards have been preposed, ritopt follows the conventions prescribed in the opt package.

    0 讨论(0)
  • 2020-11-22 00:44

    If you are already using Spring Boot, argument parsing comes out of the box.

    If you want to run something after startup, implement the ApplicationRunner interface:

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

    Your run method will be invoked after the context has started up successfully.

    If you need access to the arguments before you fire up your application context, you can just simply parse the application arguments manually:

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

    And finally, if you need access to your arguments in a bean, just inject the ApplicationArguments:

    @Component
    public class MyBean {
    
       @Autowired
       private ApplicationArguments arguments;
    
       // ...
    }
    
    0 讨论(0)
提交回复
热议问题