使用Ant通过命令行参数运行程序

Vic*_*iuk 56 java ant

我的程序获取命令行参数.当我使用Ant时,如何通过它?

emo*_*ory 72

延伸理查德库克的答案.

以下是ant运行任何程序(包括但不限于Java程序)的任务:

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>
Run Code Online (Sandbox Code Playgroud)

这是从.jar文件运行Java程序的任务:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>
Run Code Online (Sandbox Code Playgroud)

您可以从命令行调用,如下所示:

ant -Darg0=Hello -Darg1=World run
Run Code Online (Sandbox Code Playgroud)

确保使用-Darg语法; 如果你跑这个:

ant run arg0 arg1
Run Code Online (Sandbox Code Playgroud)

然后ant会尝试运行目标arg0arg1.

  • exec任务(http://ant.apache.org/manual/Tasks/exec.html)将运行任意程序.java任务(http://ant.apache.org/manual/Tasks/java.html)将执行java程序. (3认同)

ofa*_*vre 28

如果您不想为每个可能的参数处理单独的属性,我建议您使用:

<arg line="${args}"/>
Run Code Online (Sandbox Code Playgroud)

您可以检查属性是否未使用具有unless属性的特定目标设置并且在内部执行:

<input message="Type the desired command line arguments:" addProperty="args"/>
Run Code Online (Sandbox Code Playgroud)

把它们放在一起给出了:

<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>
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用它:

ant
ant run
ant run -Dargs='--help'
Run Code Online (Sandbox Code Playgroud)

前两个命令将提示命令行参数,而后者则不会.


Mar*_*nor 11

将参数传递给构建的唯一有效机制是使用Java属性:

ant -Done=1 -Dtwo=2
Run Code Online (Sandbox Code Playgroud)

以下示例演示了如何检查并确保将预期参数传递到脚本中

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>
Run Code Online (Sandbox Code Playgroud)