java-commons-cli使用

测试环境

使用commons-cli可以方便的解析java参数main(String[] args)

1
2
3
4
5
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// https://blog.csdn.net/yamaxifeng_132/article/details/87822812
public static void main(String[] args) {
Options options = new Options();
options.addOption("h", "help", false, "print options' information");
options.addOption("p", "port", true, "http proxy port");
options.addOption("s", "start", false, "commond: start http proxy server");
CommandLineParser parser = new DefaultParser();

try {
CommandLine cli = parser.parse(options, args);
if(cli.hasOption("h")){
HelpFormatter hf = new HelpFormatter();
hf.printHelp("Options", options);
}else {
String port = cli.getOptionValue("p");
int portInt = 8580;
if(port!=null){
portInt = Integer.parseInt(port);
}
System.out.println(port);
System.out.println(System.getProperty("logback.configurationFile"));
}
} catch (ParseException e) {
e.printStackTrace();
}
}

命令行运行jar

  • 短命令java -jar xx.jar -p=8888 -s
  • 长命令java -jar xx.jar -port=8888 -start
  • 带jvm参数 java -jar -Dlogback.configurationFile=./conf/logback.xml xx.jar -p=8888 -s