ant的安装与使用

    Apache Ant是一个Java库和命令行工具,其任务是将构建文件中描述的进程作为相互依赖的目标和扩展点。Ant的主要用途是构建Java应用程序。Ant提供了许多允许编译,组装,测试和运行Java应用程序的内置任务。Ant还可以有效地用于构建非Java应用程序,例如CC ++应用程序。更一般地说,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文件,如图所示


猜你喜欢

转载自blog.csdn.net/isyslab/article/details/80068923
今日推荐