Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

I looked here but didn't quite understand what I should do.

Also, 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" 
like image 450
phedon rousou Avatar asked Apr 11 '12 14:04

phedon rousou


People also ask

How do I pass a command line argument in maven?

Passing an Argument to MavenMaven will use the value (2.5) passed as an argument to replace the COMMON_VERSION_CMD property set in our pom. xml. This is not limited to the package command — we can pass arguments together with any Maven command, such as install, test, or build.

Can Java take command line arguments?

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of String s.


1 Answers

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, as decribed here, 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'" 
like image 167
Behe Avatar answered Oct 15 '22 12:10

Behe