Maven: 如何从命令行传递参数运行.java 文件

我有以下问题。我想从命令行为 Main.java文件运行 mvnMain.java接受一个参数。如何从命令行执行此操作?

我试图找到一个例子,但我没有成功。有人能给我举个例子吗?

我看了看 给你,但不太明白我应该做什么。

还有 如何从与 Main.java 文件夹不同的文件夹执行该命令?

例如,Main.java位于 my/java/program/Main.java。 我该放什么

mvn exec:java -Dexec.mainClass="what to put here?" -Dexec.args="arg0 arg1 arg2"
123788 次浏览

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'"

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

this aproach is half line command , half .pom file . you can put your args in a plugin inside the <build> </build> tag like this

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>%classpath your.package.MainClass</mainClass>
<arguments>
<argument>your_arg</argument>
</arguments>
</configuration>
</plugin>

now your arg is in the pom file . then just execute this in the command line

mvn clean compile exec:java

you can put many args :

       <arguments>
<argument>your_arg1</argument>
<argument>your_arg2</argument>
<argument>your_arg3</argument>
</arguments>