How do I parse command line arguments in Java?

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

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

19条回答
  •  天涯浪人
    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     input file path
     -o,--output    output file
    

提交回复
热议问题