通过CLI在Java中传递参数 [英] Passing argument in java through CLI
本文介绍了通过CLI在Java中传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过 CLI 在 Java 中传递参数时,我们通常像
While passing arguments in Java through CLI we generally pass like
java -cp jar classname "args[0]" "args[1]"
我想传递类似-host主机名--user用户名--password密码
等.
请帮助我实现这一目标.
Please help me in achieving this.
预先感谢!
推荐答案
您可以按以下方式使用 commons-cli 库:
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");
}
}
这篇关于通过CLI在Java中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文