Apache Ant是一個Java庫和命令行工具,其任務是將構建文件中描述的進程作爲相互依賴的目標和擴展點。Ant的主要用途是構建Java應用程序。Ant提供了許多允許編譯,組裝,測試和運行Java應用程序的內置任務。Ant還可以有效地用於構建非Java應用程序,例如C或C ++應用程序。更一般地說,Ant可以用來試驗任何類型的過程,可以用目標和任務來描述。Ant非常靈活,不會將編碼約定或目錄佈局強加給採用它作爲構建工具的Java項目。
1)Ant環境的安裝配置
安裝Ant需要JDK的支持,請先確保已經安裝了對應版本的JDK。本次選擇Ant版本爲1.10.2,對應的JDK版本爲1.8以上,環境爲centos7系統。
a)下載Ant,Ant下載地址爲:http://ant.apache.org/bindownload.cgi,此處選擇apache-ant-1.10.2-bin.tar.gz壓縮包。
b)配置環境變量:添加如下兩行到當前用戶根目錄下的/etc/profile裏。
export ANT_HOME=/pot/apache-ant-1.10.2 #ANT_HOME爲ant文件存放目錄位置
export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
c)更新/etc/profile文件,執行以下命令
[root@localhost~]# source /etc/profile
d)驗證是否安裝成功,執行以下命令,查看版本信息,結果如圖所示
[root@localhost~]# ant -version
2)利用ant構建java工程
Ant的構件文件是基於XML編寫的,默認名稱爲build.xml。爲了更清楚的瞭解Ant,在這裏編寫一個簡單的Ant程序,實現前面的詞頻統計實例。
a)新建名爲wordCount的Java工程目錄,建立src目錄爲源代碼目錄,在src目錄下建立WordCount.javal類文件,在test根目錄下面建立bulid.xml文件。
b)編輯bulid.xml文件,實現編譯src目錄下的java文件,並將編譯後的class文件放入build/classes目錄中。添加如下內容到bulid.xml文件:
<project name="HadoopCookbook" default="build" 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="hadoop.home" location="/home/hadoop/hadoop-2.9.0" />
<target name="init">
<!-- Create the time stamp -->
<tstamp />
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}" />
<mkdir dir="${build}/classes" />
</target>
<target name="compile" depends="init" description="compile the source ">
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}/classes" includeantruntime="false">
<classpath>
<fileset dir="${hadoop.home}/share/hadoop">
<include name="**/*.jar" />
</fileset>
<!-- <fileset dir="${hadoop.home}">-->
<!-- <include name="hadoop-core-*.jar" />-->
<!-- </fileset>-->
</classpath>
</javac>
</target>
<target name="build" depends="compile" description="generate the distribution">
<!-- Build the jar file -->
<jar jarfile="${build}/lib/WordCount.jar" basedir="${build}/classes" />
</target>
<target name="clean" description="clean up">
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}" />
</target>
</project>
e) 進入到wordCount目錄,執行ant build命令,結果如圖所示
f)查看生成的jar文件,如圖所示
dhp 2018.04.26