Tuesday, October 9, 2012

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

0 comments:

Post a Comment