125

How do I pass parameters to a JAR file at the time of execution?

nwinkler
  • 52,665
  • 21
  • 154
  • 168

5 Answers5

172

To pass arguments to the jar:

java -jar myjar.jar one two

You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf file of a JAR).

String one = args[0];  
String two = args[1];  
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Reji
  • 3,426
  • 2
  • 21
  • 25
46

The JAVA Documentation says:

java [ options ] -jar file.jar [ argument ... ]

and

... Non-option arguments after the class name or JAR file name are passed to the main function...

Maybe you have to put the arguments in single quotes.

realPK
  • 2,630
  • 29
  • 22
Xn0vv3r
  • 17,766
  • 13
  • 58
  • 65
18

You can do it with something like this, so if no arguments are specified it will continue anyway:

public static void main(String[] args) {
    try {
        String one = args[0];
        String two = args[1];
    }
    catch (ArrayIndexOutOfBoundsException e){
        System.out.println("ArrayIndexOutOfBoundsException caught");
    }
    finally {

    }
}

And then launch the application:

java -jar myapp.jar arg1 arg2
stratagem
  • 525
  • 6
  • 7
  • 24
    You should never use exceptions to steer your code. Instead, you should check the length of the array before acessing it! – chuck258 Sep 30 '15 at 11:04
  • 1
    Well, if the program must ALWAYS have one or more parameters, having none is IMHO a legitimate case for using an exception. – MikeW Nov 06 '18 at 14:38
8
java [ options ] -jar file.jar [ argument ... ]

if you need to pass the log4j properties file use the below option

-Dlog4j.configurationFile=directory/file.xml


java -Dlog4j.configurationFile=directory/file.xml -jar <JAR FILE> [arguments ...]
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Bachan Joseph
  • 347
  • 4
  • 5
2

Incase arguments have spaces in it, you can pass like shown below.

java -jar myjar.jar 'first argument' 'second argument'
SuperNova
  • 25,512
  • 7
  • 93
  • 64