Sunday, June 21, 2009

How to run java class using ant script, getting started with ANT, ANT easy example with java

It is very easy to compile and run any java file using ANT Script.

1. Write one build.xml (Ant Sciprt)
2. Write one java file First.java
3. Ant jar file should in classpath
4. Java compiler should also in classpath

First.java (C:\AntExample\src\First.java)

public class First {
public static void main(String[] args) {
System.out.println("Fist Data :: "+args[0]);
System.out.println("Second Data :: "+args[1]);
}
}

build.xml (C:\AntExample\build.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project name="check" basedir="." default="execute">
<property name="build_dir" value="build/class"/>
<property name="src_dir" value="src"/>

<target name="init">
<echo> Build folder crateing .......... </echo>
<mkdir dir="${build_dir}"/>
</target>

<target name="build" depends="init">
<echo> Compilation going on .......... </echo>
<javac destdir="${build_dir}" srcdir="${src_dir}"/>
</target>

<target name="execute" depends="init,build">
<echo> Running java class ......... </echo>
<javaclassname = "First" classpath="${build_dir}">
<arg value="10"/>
<arg value="20"/>
</java>
</target>
</project>

Now run the ant scriptc:\AntExample> ant You will get output like this
Buildfile: C:\AntExample\build.xml
init:
[echo] Build folder crateing ..........
build:
[echo] Compilation going on ..........
execute:
[echo] Running java class .........
[java] Fist Data :: 10
[java] Second Data :: 20
BUILD SUCCESSFULTotal time: 468 milliseconds

You will get one build\class folder inside the AntExample folder having First.class file

11 comments:

  1. Replies
    1. can u help me..what we have to give in src_dir and build_dir in the above example

      Delete
  2. my guess, missing space at: <java classname = "First"

    ReplyDelete
    Replies
    1. can u help me..what we have to give in src_dir and build_dir in the above example

      Delete
  3. my guess is that it is at: <java classname = "First"

    ReplyDelete
  4. what path we have to give in build_dir and src_dir in the above example

    ReplyDelete
  5. what is the path we have to give in src_dir and build_dir in the above example

    ReplyDelete
  6. can any one help me..what we have to give in src_dir and build_dir in the above example

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)