Jatinder Brar
Jatinder Brar

Reputation: 27

How to run java program with ant

I am a complete noob in Java and I want to know how do you run a Java program after you use build.xml. I am using 'cmd' and I got the message BUILD SUCCESSFUL after compiling (?) Now what should I do to run the program?

Edit: it created a .war file. How do I execute it?

Upvotes: 1

Views: 14793

Answers (2)

user6743474
user6743474

Reputation:

Not assuming everything is in the root directory, a far better solution is available on the apache ant page that parameterizes all the directories etc. and is a more general and practical answer. Tutorial: Hello World with Apache Ant

<project name="Hello World" basedir=".">        
        <mkdir dir="build/classes"/>
        <javac
            srcdir="src"
            destdir="build/classes"/>
        <!-- automatically detected -->
        <!-- obsolete; done via manifest tag -->
        <mkdir dir="build/jar"/>
        <jar
            destfile="build/jar/HelloWorld.jar"

            basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="org.HelloWorld"/>
            </manifest>
        </jar>
        <java jar="build/jar/HelloWorld.jar" fork="true"/>
    
    <target name="compile">
           <javac includeantruntime="true" includes="HelloWorld.java"></javac>
    </target>           
    
    <target name="run" depends="compile">
           <java classname="bin/org/HelloWorld" fork="true"></java>      
        <echo message="Event Generator Finished."/>
    </target>
</project>

Upvotes: 0

Aroonalok
Aroonalok

Reputation: 689

I assume that this is a simple "Hello, World" Java program (HelloWorld.java) and that the HelloWorld.java, build.xml and the HelloWorld.class (to be generated) are in the current directory (.)

HelloWorld.java file :

public class HelloWorld {

public static void main(String[] args) {
    // Prints "Hello, World" to the terminal window.
    System.out.println("Hello, World");
}

}

Create two targets : compile and run in your build.xml file :

<project name="Hello World" basedir=".">

<target name="compile">
       <javac srcdir="." includeantruntime="true" includes="HelloWorld.java" destdir="."></javac>
</target>

<target name="run" depends="compile">
       <java classname="HelloWorld" fork="true"></java>
</target>

</project>

Now you simply need to navigate to the current directory in your terminal and run :

ant run

Upvotes: 7

Related Questions