My program getting command line arguments. How can I pass it when I use Ant?
To run the ant build file, open up command prompt and navigate to the folder, where the build. xml resides, and then type ant info. You could also type ant instead. Both will work,because info is the default target in the build file.
If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.
Command Line. If you've installed Apache Ant as described in the Installing Ant section, running Ant from the command-line is simple: just type ant . When no arguments are specified, Ant looks for a build.
Extending Richard Cook's answer.
Here's the ant
task to run any program (including, but not limited to Java programs):
<target name="run"> <exec executable="name-of-executable"> <arg value="${arg0}"/> <arg value="${arg1}"/> </exec> </target>
Here's the task to run a Java program from a .jar
file:
<target name="run-java"> <java jar="path for jar"> <arg value="${arg0}"/> <arg value="${arg1}"/> </java> </target>
You can invoke either from the command line like this:
ant -Darg0=Hello -Darg1=World run
Make sure to use the -Darg
syntax; if you ran this:
ant run arg0 arg1
then ant
would try to run targets arg0
and arg1
.
If you do not want to handle separate properties for each possible argument, I suggest you'd use:
<arg line="${args}"/>
You can check if the property is not set using a specific target with an unless
attribute and inside do:
<input message="Type the desired command line arguments:" addProperty="args"/>
Putting it all together gives:
<target name="run" depends="compile, input-runargs" description="run the project"> <!-- You can use exec here, depending on your needs --> <java classname="Main"> <arg line="${args}"/> </java> </target> <target name="input-runargs" unless="args" description="prompts for command line arguments if necessary"> <input addProperty="args" message="Type the desired command line arguments:"/> </target>
You can use it as follows:
ant ant run ant run -Dargs='--help'
The first two commands will prompt for the command-line arguments, whereas the latter won't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With