Passing argument in java through CLI

前端 未结 4 1806
说谎
说谎 2021-01-23 01:16

While passing arguments in Java through CLI we generally pass like

java -cp jar classname \"args[0]\" \"args[1]\"

I want to

4条回答
  •  离开以前
    2021-01-23 01:53

    You can use commons-cli library as follows:

    import org.apache.commons.cli.*;
    
    public class Main {
    
    
        public static void main(String[] args) throws Exception {
    
            Options options = new Options();
    
            Option host = new Option("h", "host", true, "host address");
            host .setRequired(true);
            options.addOption(host);
    
            Option user = new Option("u", "user", true, "user login");
            user.setRequired(true);
            options.addOption(user);
    
            Option password = new Option("p", "password", true, "user's password");
            password.setRequired(true);
            options.addOption(password);
    
            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("my-program", options);
    
                System.exit(1);
                return;
            }
    
            String inputHost = cmd.getOptionValue("host");
            String inputUser = cmd.getOptionValue("user");
            String inputPassword = cmd.getOptionValue("password");
    
    
        }
    
    }
    

提交回复
热议问题