In this article, we will see some examples of jopt-simple framework
, a java library for parsing command line options.
Short and Long options
Parser supports long and short options. Short options begin with a single hyphen. Long options begin with two hyphens.
ShortLongOptionExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; public class ShortLongOptionExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.accepts("d"); OptionSpec<String> longOption = parser.accepts("fruit").withOptionalArg(); OptionSet options = parser.parse("-d", "--fruit=apple"); System.out.println("Has short option? " + options.has("d")); System.out.println("Has long option? " + options.has(longOption) + ": " + options.valueOf(longOption)); } }
Output:
Has short option? true Has long option? true: apple
Mandatory and Optional Arguments
Options can accept single arguments. The argument can be made required or optional.
Below example we show the case of required argument. If it is optional use withOptionalArg()
.
RequiredArgumentExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; public class RequiredArgumentExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<String> clusterOption = parser .accepts("cluster", "cluster name").withRequiredArg(); try { parser.parse("--cluster"); } catch (Exception e) { System.out.println(e); } OptionSet options = parser.parse("--cluster=xyz"); System.out.println("cluster=" + options.valueOf(clusterOption)); } }
Output:
joptsimple.OptionMissingRequiredArgumentException: Option cluster requires an argument cluster=xyz
Cluster Arguments
Below example shows a cluster of options used against a single hyphen. -abc
can be treated as -a
, -b
, -c
.
ClusterArgumentsExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSet; public class ClusterArgumentsExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.accepts("a"); parser.accepts("b"); parser.accepts("c"); OptionSet options = parser.parse("-abc"); System.out.println(options.has("a")); System.out.println(options.has("b")); System.out.println(options.has("c")); } }
Output:
true true true
Multiple arguments example
In the below example, we provide multiple arguments. We specify the options multiple times on a single command line. The parser collects any arguments specified for those options as a list.
MultipleArgumentsExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; public class MultipleArgumentsExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<String> fruits = parser.accepts("a").withRequiredArg(); OptionSet options = parser.parse("-a", "apple", "-a", "berries", "-a", "mango"); System.out.println(options.valuesOf(fruits)); } }
Output:
[apple, berries, mango]
Value Converter example
In the below example, we show an example of typed argument. We have used here PathConverter
to retrieve the argument of the associated option in a type-safe manner returning argument of type Path
.
FilePathArgumentExample:
package com.javarticles.joptsimple; import java.nio.file.Path; import java.util.Arrays; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import joptsimple.util.PathConverter; public class FilePathArgumentExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<Path>> cfgfileOption = parser.acceptsAll(Arrays.asList("c", "config"), "Loads the configuration file") .withRequiredArg() .withValuesConvertedBy(new PathConverter()); OptionSet options = parser.parse("-c", "../cfg"); Path cfgPath = options.valueOf(cfgfileOption); System.out.println("CFG Path: " + cfgPath); } }
Output:
CFG Path: ..\cfg
Mutually exclusive arguments
We can also provide options which are mutually exclusive on a command line.
MutuallyExclusiveArgumentsExample:
package com.javarticles.joptsimple; import java.util.Arrays; import joptsimple.OptionParser; public class MutuallyExclusiveArgumentsExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.mutuallyExclusive( parser.acceptsAll( Arrays.asList( "ftp", "file-transfer" ) ), parser.accepts( "file" ), parser.accepts( "http" ) ); try { parser.parse("--ftp", "--file"); } catch(Exception e) { System.out.println(e); } parser.parse("--ftp"); } }
Output:
joptsimple.UnavailableOptionException: Option(s) [file, file-transfer/ftp] are unavailable given other options on the command line
Require dependency example
Below example shows how to create required dependent options. Options userid
and password
are mandatory if the option login
is selected.
RequireDependencyExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; public class RequireDependencyExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<Void> loginSpec = parser.accepts("login"); parser.accepts("userid").requiredIf("login").withRequiredArg(); parser.accepts("password").requiredIf("login").withRequiredArg(); try { parser.parse("--login"); } catch (Exception e) { System.out.println(e); } OptionSet options = parser.parse("--login", "--userid", "javarticles", "--password", "xyz"); if (options.has(loginSpec)) { System.out.println("Login selected"); System.out.println("userid: " + options.valueOf("userid")); } } }
Output:
joptsimple.MissingRequiredOptionsException: Missing required option(s) [password, userid] Login selected userid: javarticles
Available unless example
An option is allowed only if the given option is absent on the command.
Option verbose
will make sense only if option silent
is not specified.
AvailableUnlessExample:
package com.javarticles.joptsimple; import java.util.Arrays; import joptsimple.OptionParser; import joptsimple.OptionSpec; public class AvailableUnlessExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<Void> silentOption = parser.acceptsAll( Arrays.asList("s", "silent"), "show minimal output"); parser.acceptsAll(Arrays.asList("v", "verbose"), "show verbose output") .availableUnless(silentOption); try { parser.parse("-v", "-s"); } catch (Exception e) { System.out.println(e); } parser.parse("-v"); parser.parse("-s"); } }
Output:
joptsimple.UnavailableOptionException: Option(s) [v/verbose] are unavailable given other options on the command line
Available If example
We can also create dependent options. For example, option x is allowed if options (a, b) are present on the command line.
DependentOptionsExample:
package com.javarticles.joptsimple; import joptsimple.OptionParser; import joptsimple.OptionSpec; public class DependentOptionsExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<String> ip = parser.accepts( "ip" ).withRequiredArg().defaultsTo("localhost"); OptionSpec<Integer> port = parser.accepts( "port" ).withRequiredArg().ofType( Integer.class ).defaultsTo(6000); parser.accepts("server").availableIf(ip, port); OptionSet options = parser.parse("--server", "--ip=192.168.0.5", "--port=6000"); System.out.println(options.valueOf(ip) + ":" + options.valueOf(port)); } }
Output:
192.168.0.5:6000
Help command example
We can designate an option as a “help” option. The presence of a “help” option on a command line means that missing “required” options will not cause parsing to fail.
HelpCommandExample:
package com.javarticles.joptsimple; import java.util.Arrays; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; public class HelpCommandExample { public static void main(String[] args) { OptionParser parser = new OptionParser(); OptionSpec<Void> helpOption = parser .acceptsAll(Arrays.asList("h", "help"), "show help").forHelp(); OptionSet options = parser.parse("-h"); if (options.has(helpOption)) { System.out.println("Print help..."); } } }
Output:
Print help...
Download the source code
This was an example about java command line parsing framework jopt-simple. You can download the source code here
joptSimpleExample.zip