Java Command line arguments

133,155

Solution 1

public class YourClass {
    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("a")){
            //...
        }
    }
}

Solution 2

Use the apache commons cli if you plan on extending that past a single arg.

"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."

Commons CLI supports different types of options:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)

Solution 3

Every Java program starts with

public static void main(String[] args) {

That array of type String that main() takes as a parameter holds the command line arguments to your program. If the user runs your program as

$ java myProgram a

then args[0] will hold the String "a".

Solution 4

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}

Solution 5

Command line arguments are accessible via String[] args parameter of main method.

For first argument you can check args[0]

entire code would look like

public static void main(String[] args) {
    if ("a".equals(args[0])) {
         // do something
    }
}
Share:
133,155
burntsugar
Author by

burntsugar

Trainer. Student. Developer. Java, Android, Sushi, CAPSLOCK. Concentrates really hard. Especias Secreto. Melbourne Australia.

Updated on July 22, 2022

Comments

  • burntsugar
    burntsugar almost 2 years

    I am trying to detect whether the 'a' was entered as the first string argument.