Ant的使用

来源:互联网 发布:win7网络克隆工具 编辑:程序博客网 时间:2024/05/21 08:45

  这些天刚上线一个项目,找了个机会温故一下ant的使用,也是为新手们提供一个学习ant的东西吧。

  首先我会提供一个ant的模板,ant的默认文件是build.xml,我想刚开始接触web开发的新人们,也会很奇怪这个在项目根目录下的xml东西是干嘛用的。其实它就是大名鼎鼎的ant默认文件,部署和发布一个项目的最佳利器。下面就是我用的项目的一个实际应用模板:

   

大家看了是不是有点害怕,其实并不用太担心,接下我就解释一下ant的关键元素以及最重要的ant的常用的方法:

1.Ant的关键元素

  project:是Ant的根元素,每一个ant文件至少包含一个project元素。其中包含多个target

                属性有name(项目名称),default(默认执行target名称),basedir(用于指定基路径的位置,未指定时默认为ant文件的父目录                 路径)

   

 

  target:它为ant的基本执行单元,包括一个或多个任务,特别多个target可以存在项目的依赖关系。

             属性:name

                      depends

                      if

                      unless

                      description

 

 

  property:它可以看作参数和参数的定义,project的属性可以通过property来设定,如果要在外部引入某文件,例如build.properties,<property file="build.properties"/>,而且也可以作为task的属性值。

 

 2.Ant的常用方法

 在Ant文件里,每一个target都封装了要执行的功能。是ant工具的基本执行单位。

  copy 任务:该任务主要是用对文件和目录的复制功能。

  1)复制单个文件:<copy file="file.txt" tofile="copy.txt"/>;

  2)对文件目录进行复制:

        <copy todir="../newdir/dest_dir">

               <fileset dir="src/src_dir"/>

        </copy>

  3)将文件复制到另为的目录:<copy file="file.txt" todir="../newdir/dest_dir"/>

 

 delete 任务:该任务负责删除文件和目录

  1)删除某个文件: <delete file="file.txt"/>

  2)删除某个目录:<delete dir="src"/>

  3)删除所有的备份目录和空目录:<delete includeEmptyDirs="true">

                                                        <fileset dir="." includes="**/*.bak"/>

                                               </delete>

 mkdir 任务:创建目录,<mkdir dir="build"/>

 

 move 任务:移动文件或目录

 1)移动单个文件: <move file="file.txt" tofile="tofile.txt"/>

 2)移动单个文件到另一个目录:<move file="file.txt" todir="../newdir“/>

 3)移动某个目录到另一个目录:<move todir="../newdir">

                                                <fileset dir="build"/>

                                           </move>

 echo 任务:该任务根据日志和监控器级别输出信息。它包括:message,file,append和level四个属性

                  <echo message="hello,world" file="logging.log" append="true"/>

 

*利用ant构建和部署java工程

Ant可以代替javac java 和jar命令来执行java操作,从而轻松完成构建和部署java工程的工作。

 

<!-- Compile Target 编译代码,在这之前先由prepare建立目录结构 -->  

<target name="compile" depends="prepare" description="Compile java sources">

<!-- Compile java class as necessary -->

<javac srcdir="${src.dir}" destdir="${classes.dir}" encoding="utf-8" debug="true" debuglevel="source,lines,vars"  includeantruntime="on">

<classpath refid="compile.classpath"/>

</javac>

</target>

 

 

*使用ant的war任务来给java EE项目打包

 <!-- Dist Target 将应用打包成线上环境使用的war-->  

<target name="dist" depends="clean,compile" description="create war file for the fomal envionment">

<copy todir="${classes.dir}">

<fileset dir="${www.dir}">

<exclude name="*.svn"/>

<include name="**/*.xml"/>

           <include name="**/*.properties" />

</fileset>

</copy>

<jar jarfile="${dist.dir}/${appName}.war" basedir="${webroot.dir}"/>

</target>