Java 解析 args 参数
🏷️ Java
这里是使用 Commons-CLI
的示例,原文中还有使用 Args4J
和 JCommander
的示例。
java
package com.ocotopus.octpusapiservices;
import org.apache.commons.cli.*;
import java.util.Date;
/**
* Created by liujiajia on 2017/2/16.
*/
public class ArgsTest {
public static void main(String[] args) {
args = new String[]{"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s10", "-Dkey1=value1", "-Dkey2=value2" };
try {
// create Options object
Options options = new Options();
options.addOption(new Option("t", "text", true, "use given information(String)"));
options.addOption(new Option("b", false, "display current time(boolean)"));
options.addOption(new Option("s", "size", true, "use given size(Integer)"));
options.addOption(new Option("f", "file", true, "use given file(File)"));
@SuppressWarnings("static-access")
Option property = OptionBuilder.withArgName("property=value")
.hasArgs(2)
.withValueSeparator()
.withDescription("use value for given property(property=value)")
.create("D");
property.setRequired(true);
options.addOption(property);
// print usage
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "AntOptsCommonsCLI", options );
System.out.println();
// create the command line parser
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
// check the options have been set correctly
System.out.println(cmd.getOptionValue("t"));
System.out.println(cmd.getOptionValue("f"));
if (cmd.hasOption("b")) {
System.out.println(new Date());
}
System.out.println(cmd.getOptionValue( "s" ));
System.out.println(cmd.getOptionProperties("D").getProperty("key1") );
System.out.println(cmd.getOptionProperties("D").getProperty("key2") );
} catch (Exception ex) {
System.out.println( "Unexpected exception:" + ex.getMessage() );
}
}
}
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
执行结果:
bash
usage: AntOptsCommonsCLI
-b display current time(boolean)
-D use value for given property(property=value)
-f,--file use given file(File)
-s,--size use given size(Integer)
-t,--text use given information(String)
rensanning
c:/aa.txt
Thu Feb 16 14:14:51 CST 2017
10
value1
value2
Process finished with exit code 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15