How to run a java file from command line passing arguments in Maven

0 votes

I have the following problem. I would like to run mvn from command line for a Main.java file. Main.java accepts a parameter. How do I do that from command line?

I tried finding an example but I was not successful. Could someone help me by giving me an example of that?

How do I execute that command from a different folder than the Main.java folder?

For example the Main.java is located in my/java/program/Main.java. What should I put in

mvn exec:java -Dexec.mainClass="what to put here?" -Dexec.args="arg0 arg1 arg2"
Jun 3, 2020 in Java by kartik
• 37,510 points
20,499 views

1 answer to this question.

0 votes

Hello @kartik,

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"


Hope this helps and to know more about running Java file, join one of our Java certification course now.

answered Jun 3, 2020 by Niroj
• 82,880 points