Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Ant for running program with command line arguments

Tags:

java

ant

My program getting command line arguments. How can I pass it when I use Ant?

like image 952
Victoria Seniuk Avatar asked Sep 16 '10 21:09

Victoria Seniuk


People also ask

How do I run an Ant project from the command line?

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.

How do I pass a command line argument to a program?

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.

What is Ant in command line?

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.


2 Answers

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.

like image 174
emory Avatar answered Sep 25 '22 03:09

emory


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.

like image 22
ofavre Avatar answered Sep 23 '22 03:09

ofavre