使用Apache Ant编译打包运行Java项目

环境:

1,OS:Windows7

2,JDK:jdk1.7

3,Apache Ant:apache-ant-1.9.6

Ant安装步骤:

1,解压apache-ant-1.9.6-bin.zip

2,添加环境变量ANT_HOME,比如C:\apache-ant-1.9.6-bin

3,Path变量添加ant的bin目录,比如%ANT_HOME%\bin

编译运行Java工程目标流程:

0,准备好必要的项目运行库${lib}/*.jar,准备好源工程文件夹及文件${basedir}/src/*,准备好项目需要的配置文件${basedir}/conf/*

1,建立临时编译文件夹${basedir}/bin/classes

2,批量编译Java文件

3,编译好的src package打包为jar、移动,删除临时目录

4,运行Java项目

Ant build.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project name="javaprjtest" default="run" basedir=".">
	
	<property name="src" value="${basedir}/src"></property>
	<property name="dest" value="${basedir}/bin/classes"></property>
	<property name="lib" value="${basedir}/lib"></property>
	<property name="jarname" value="testprj1.jar"></property>	
	
	<!-- 引入java库文件  -->
	<path id="classpath">  
		<fileset dir="${lib}">  
			<include name="*.jar"/>  
		</fileset>
	</path>
	
	<property name="classpath" refid="classpath"/> 
	
	<target name="clean" description="clean folder:" >
		<delete dir="${dest}"></delete>		
	</target>

	<target name="init" description="Create folder:" >
		<mkdir dir="${dest}"/>
	</target>
	
	<!-- 批量编译  -->
	<target name="compile" >		
		<javac  srcdir="${src}" 
				destdir="${dest}" 
				description="Compiling:" 
				encoding="utf-8" 
				classpath="${classpath}" 
				debug="true">
		</javac>	
	</target>
	
	<!-- 复制xml文件  -->
	<target name="cp" depends="compile">
		<copy todir="${dest}" >
			<fileset dir="${src}">
				<include name="**/*.xml"/>
			</fileset>
		</copy>
	</target>
	
	<!-- 打包  -->
	<target name="build">	
		<jar destfile="${jarname}" basedir="${dest}" ></jar>
	</target>
	
	<!-- 移动 -->
	<target name="mv">
		<move todir="${lib}" file="${jarname}"></move>
		<delete dir="${dest}"></delete>
	</target>
		
	<!-- 启动Java程序-->
	<target name="run" depends="clean,init,compile,cp,build,mv">
		<java classname="com.test.MainPro" classpathref="classpath"  fork="true" dir="${lib}">
		</java>		
	</target>
	
</project>



猜你喜欢

转载自fall10.iteye.com/blog/2315314