visit
The is typically the entry point for a Java class. The JVM passes the command line argument through the
String[] args
parameter of the main() method
, so you can fetch these arguments by accessing this parameter.Let’s look at a simple Java command line application:To compile the program from command line, use where SimpleCommandLinePgm.java is the name of your Java file:class SimpleCommandLinePgm { public static void main(String[] args) { System.out.println("This is a simple command line program!"); System.out.println("Your Command Line arguments are:"); // loop through all arguments and print it to the user for (String str: args) { System.out.println(str); } } }
javac SimpleCommandLinePgm.java
This will compile your Java application and create a
.class
file, which can be executed with the java command.Executing a Java Command Line Script with One Argument
arguments typically follow the name of the program when it is executed, so to execute your newly compiled class, run the following from your terminal:java SimpleCommandLinePgm one
SimpleCommandLinePgm
is the name of the compiled Java program without .java
extension.one
your first command line argument to the programThis is a simple command line program! Your Command Line arguments are: one
Executing a Java Command Line Script with Multiple Arguments
Now that you’ve executed a Java command line class with one argument, let’s look at how this changes with multiple command line arguments:java SimpleCommandLinePgm one two three four
This command looks almost the same, but as you can see, there are now four arguments after the name of the program (
one two three four
). Each item in your list of command line arguments is separated by space.This time, you’ll see something like this:This is a simple command line program! Your Command Line arguments are: one two three four
Executing a Java Command Line Script with Named Arguments
Allowing users to enter named arguments into a Java command line application makes your program much more flexible. It allows users to leave out some arguments, and it makes your interface more intuitive as users running the application can tell what each argument might do based on the key name.By default, Java doesn't accept key-value pairs via the CLI. However, the arguments can be passed using the , which passes the key-value pair arguments as arguments to the JVM itself.This class shows how the key value pair arguments can be accessed from your Java program using the
system.getProperty()
method:public class AdvancedCommandLinePgm { public static void main() { System.out.println("This is an advanced command line program!"); // Get the value using the System.get Property and print it. System.out.println("Username is: " + System.getProperty("userName")); } }
java -Dusername=Vikram AdvancedCommandLinePgm
# Output
This is an advanced command line program!
Username is: Vikram
Using PicoCli to Parse Java Command Line Arguments
PicoCli is a single-file framework that allows you to create a Java program with almost zero code for handling command line arguments. It supports multiple command line syntax styles, including POSIX, GNU, MS-DOS, and it can generate highly customizable help messages with ANSI styles and colors to highlight important elements.To use the PicoCli, you need the in your buildpath, classpath, or (depending on your project configuration).PicoCli can be implemented , which makes it easy for you to create a runnable Java program. Here’s an example of a simple PicoCli class:@Command(name = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile information.") class PicoCliSamplePgm implements Runnable { }
The annotation
@Command
for the class denotes that this is a command line program. Here, I’m using several attributes for the @Command
annotation:PicoCli supports both named and positional arguments. For example, the following annotation shows how named arguments (called options by PicoCli) are defined:
@Option(names = { "-f", "--firstname" }, required = true, description = "First Name of the user") private String firstName = "First Name";
Positional arguments (called parameters) don't have names and are mandatory by default. This example shows how you can define a positional parameter in PicoCli:
@Parameters(index = "0") private String country;
@Command(name = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile information.") class PicoCliSamplePgm implements Runnable { @Option(names = { "-f", "--firstname" }, required = true, description = "First Name of the user") private String firstName = "First Name"; @Option(names = { "-l", "--lastname" }, required = true, description = "Last name of the user") private String lastName = "Last Name"; @Option(names = { "-e", "--email" }, required = true, description = "email id of the user") private String email = "email"; // Positional Parameters @Parameters(index = "0") private String country; @Option(names = { "-m", "--mobilenumber" }, required = false, description = "Mobile Number of the user") private String mobileNumber; @Override public void run() { // your business logic goes here... System.out.println("User First Name is: " + firstName); System.out.println("User Last Name is: " + lastName); System.out.println("User Email is: " + email); if (mobileNumber != null) { System.out.println("User Mobile Number is: " + mobileNumber); } if (country != null && !country.isEmpty()) { System.out.println("(Positional parameter) User's country is: " + country); } } // This example implements Runnable, so parsing, error handling, and help messages can be done with this line: public static void main(String... args) { int exitCode = new CommandLine(new PicoCliSamplePgm()).execute(args); System.exit(exitCode); } }
# Note: Depending how you include the PicoCli library, your command may vary. java -cp "myapp.jar;picocli-4.5.2.jar" PicoCliSamplePgm -f Vikram -l Aruchamy -e [email protected] India -m 123456789 # Output: User First Name is: Vikram User Last Name is: Aruchamy User Email is: [email protected] User Mobile Number is: 123456789 (Positional parameter) User's country is: India
Using Apache Commons CLI to Parse Java Command Line Arguments
Apache Commons CLI is another commonly used library in Java for command line parsing. It’s a good choice if you just need basic command line functionality and are already using other Apache libraries like .To use the Apache Commons CLI, you need the in your buildpath, classpath, or the Maven repository.You can define command line options using the and objects available in Commons CLI.
Options
offers a list to hold all your program’s options, while Option
lets you define the characteristics of each parameter individually.To parse command line parameters, Commons CLI uses the implementation of the
CommandlineParser
interface. DefaultParser
has a method called parse()
which accepts the options
object and the args
from the command line. Finally, you can use the HelpFormatter
to print the help information to the user.The below example shows you a complete example of the Apache Commons CLI:public class CommonsCliPgm {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option name = new Option("f", "name", true, "First Name");
name.setRequired(true);
options.addOption(name);
Option lastName = new Option("l", "lastname", true, "Last Name");
lastName.setRequired(true);
options.addOption(lastName);
Option email = new Option("e", "email", true, "Email");
email.setRequired(true);
options.addOption(email);
Option mobileNumber = new Option("m", "mobilenumber", true, "Mobile Number");
mobileNumber.setRequired(false);
options.addOption(mobileNumber);
HelpFormatter formatter = new HelpFormatter();
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("User Profile Info", options);
System.exit(1);
return;
}
System.out.println("User First Name is: " + cmd.getOptionValue("name"));
System.out.println("User Last Name is: " + cmd.getOptionValue("lastname"));
System.out.println("User Email is: " + cmd.getOptionValue("email"));
if (cmd.hasOption("m")) {
System.out.println("User Mobile Number is: " + cmd.getOptionValue("mobilenumber"));
}
}
}
Now you can run the program with optional
-m
parameter:java CommonsCliPgm -f Vikram -l Aruchamy -e [email protected] -m 123456789 # Output User First Name is: Vikram User Last Name is: Aruchamy User Email is: [email protected] User Mobile Number is: 123456789
Or without the optional parameter:
java CommonsCliPgm -f Vikram -l Aruchamy -e [email protected]
# Output
User First Name is: Vikram
User Last Name is: Aruchamy
User Email is: [email protected]
Auto-complete and suggestions to speed up your developmentLine-by-line (rather than using
System.println())Version
control system integration that makes it easier to track changes to your codeIn this section, you'll learn how to test and run command line scripts using the . This section assumes you've already set up and have a working command line program (like one of the ones above).Command Line Arguments in Eclipse IDE
In Eclipse, right-click on the class you want to run. In the context menu, select Run As -> Java Application. It will run the program:
If your command line program requires specific arguments, you'll see an error saying that command line parameters are missing. Behind the scenes, Eclipse will create a configuration. To add your arguments, right-click again and select Run -> Run Configuration.
Eclipse will show you all the run configurations available in the workspace. Select the class name on the left side and enter your command line parameters, as shown in the below image.Click Run. You'll see output based on your command line parameters.
User First Name is: Vikram User Last Name is: Aruchamy User Email is: [email protected] User Mobile Number is: 123456798 (Positional parameter) User's country is: India
Command Line Arguments in IntelliJ
In IntelliJ, the process is similar. Right-click on the class, and in the context menu, select Run PicoCliSamplePgm.Main():
It will run the program and if arguments are required, show an error. Now IntelliJ has created a configuration, so you can select Run -> Run Configurations. Select the class name on the left side as shown below and enter your command line parameters in the Program Arguments option. Click Ok.
Run your program again using the
Run
option in the right-click context menu. You’ll see output based on your command line parameters.Previously published at