20 Dec 2014

Compile & Run a Java program Using ANT

By using ANT, it is very easy and straight forward procedure to compile and run a java program. All we need is to configure ant build process for only one time, i.e for first time.

Let us see how to compile and run a simple java hello world program by using ANT.
  1. Create a project as D:\project1 and create two folders src & classes inside the project folder for keeping source(.java) & class(.class) files as shown below:


  2. Inside src folder, create a java program ‘Hello.java’ inside com.app package.
    package com.app;
    
    public class Hello{
    
       public static void main(String args[]){
          System.out.println("Hello World");
       }
    
    }
    
    Hello.java

  3. In order to compile and run this java program with ant tool we need an xml file named as build.xml as shown below:
    <project default="run">
       <target name="compile">
          <javac srcdir="src" destdir="classes" />
       </target>
       
       <target name="run" depends="compile">
          <javac classpath="classes" classname="com.app.Hello" />
       </target>
    </project>
    
    build.xml

  4. Now everything is done for build process. Try to run ant command from project directory where build.xml is located so that our java program will be compiled and run by ant. Inside classes folder we can find .class file generated once compile target executed successfully.

By using the same build process we can run any java program by simply running ant command.





Popular Posts

Write to Us
Name
Email
Message