Monday, September 11, 2017

How to parse command line arguments in Java

Sometimes we need a simple parser of command line options. Here is a simple example how such a parser can be implemented in Java:


You can add more parameters to the "while" loop. Here is how it can be used:

$ javac -d . CommandLine.java 
$ java CommandLine
host    = localhost
port    = 80
verbose = false
$ java CommandLine --host test
host    = test
port    = 80
verbose = false
$ java CommandLine --host test --port 81
host    = test
port    = 81
verbose = false
$ java CommandLine --host test --port 81 --verbose
host    = test
port    = 81
verbose = true
$ java CommandLine --host test --port 81 --verbose --a
Exception in thread "main" java.lang.RuntimeException: Unexpected parameter: --a
 at CommandLine.parse(CommandLine.java:30)
 at CommandLine.main(CommandLine.java:91)
$ java CommandLine --host test --port
Exception in thread "main" java.lang.RuntimeException: No path specified for --output option
 at CommandLine.parse(CommandLine.java:21)
 at CommandLine.main(CommandLine.java:91)
$ java CommandLine --host test --port
Exception in thread "main" java.lang.RuntimeException: No path specified for --port option
 at CommandLine.parse(CommandLine.java:21)
 at CommandLine.main(CommandLine.java:91)

Enjoy!