Antの動作確認

Revised: 27th/Apr./2008; Since: 25th/Nov./2002

Antの導入ディレクトリ

Antでビルドするソースファイルの置き場所を作成します。ここでは、作業ディレクトリを"D:\java\ant\"、ソースファイルを"D:\java\ant\src\"に置きます。

D:\
  |
  +--java/
     |
     +--ant/
        |
        +--src/HelloWorld.java

ソースファイル

Javaソースファイル

いつもの"HelloWorld.java"をsrcフォルダに作成します。ここではjava.text.SimpleDateFormatクラスを用いて、java.util.Date型オブジェクトを出力しています。

import java.util.Date;
import java.text.SimpleDateFormat;

class HelloWorld {
	public static void main(String str[]) {
		System.out.println("Hello, World");
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
		System.out.println(sdf.format(date));
	}
}

build.xml

Antは、さまざまな操作をXMLファイルの要素で記述します。このXMLをbuild.xmlと呼びます。ここに記述された要素をタスクと呼び、操作できる対象は、javac, jarなどのJDKツールのほか、mkdirなど多岐に渡ります。詳細は、Antのドキュメントを参照してください。

ここでは、srcフォルダをコンパイルしてbuildフォルダへクラスファイルを生成、最後にdit/libフォルダへタイムスタンプつきのjar "MyProject-20080428.jar"を生成するbuild.xmlを用意します。

次のソースをコピーして、"D:\java\ant\helloworld.xml"を作成してください。

<project name="MyProject" default="dist" basedir=".">
    <description>
        simple example build file
    </description>
  <!-- set global properties for this build -->
  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist"  location="dist"/>

  <target name="init">
    <!-- Create the time stamp -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
  </target>

  <target name="compile" depends="init"
        description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}"/>
  </target>

  <target name="dist" depends="compile"
        description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${dist}/lib"/>

    <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
    <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
  </target>

  <target name="clean"
        description="clean up" >
    <!-- Delete the ${build} and ${dist} directory trees -->
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>
</project>

Antの実行

C:\>d:

D:\>cd java/ant

D:\java\ant>ant -buildfile helloworld.xml
Buildfile: helloworld.xml

init:
    [mkdir] Created dir: D:\java\ant\build

compile:
    [javac] Compiling 1 source file to D:\java\ant\build

dist:
    [mkdir] Created dir: D:\java\ant\dist\lib
      [jar] Building jar: D:\java\ant\dist\lib\MyProject-20080428.jar

BUILD SUCCESSFUL
Total time: 2 seconds
D:\java\ant>

Ant実行の結果、buildフォルダとdistフォルダが作成され、各々に、クラスファイルとjarファイルが生成されていることが分かります。

実行結果は次の通りです。

D:\java\ant>cd dist/lib

D:\java\ant\dist\lib>java -classpath MyProject-20080428.jar HelloWorld
Hello, World
2008-04-28T01:07:32.303+0900

D:\java\ant>
HelloWorldデプロイ結果
図:HelloWorldデプロイ結果


Copyright © 2002-2008 SUGAI, Manabu. All Rights Reserved.
SEO [PR] !uO z[y[WJ Cu