使用ant生成可执行的jar包

Ant构建Java项目
本文介绍如何使用Apache Ant构建Java项目,包括安装配置、目录结构、自定义任务扩展Ant功能及生成可执行jar包的方法。

1. a.下载ant: http://ant.apache.org/bindownload.cgi

    b.安装ant: 解压ant,路径越简单越好(这是好习惯),设置环境变量ANT_HOME,PATH里添加;%ANT_HOME%/bin

    c.打开cmd,键入ant回车,如果出现提示信息
"Buildfile: build.xml does not exist!
Build failed"
就说明安装成功了

2.  java工程目录结构:
|-src-|-  //.java源文件
|-bin-|- // .class文件
|-lib-|-  //第三方jar包
build.xml    // ant 配置文件

3。由于ant没有提供填写jar包里Class-Path的任务,所以需要编写自定义任务,扩展Ant,Java代码如下:

  1. package personal.lw.util;
  2. import java.io.File;
  3. import org.apache.tools.ant.BuildException;
  4. import org.apache.tools.ant.Task;
  5. public class AntUtil extends Task {
  6.     private String lib;
  7.     private String classPath = "";
  8.     private String fileType = ".jar";
  9.     // ant task
  10.     public void execute() throws BuildException {
  11.         try {
  12.             this.classPath(dir(lib));
  13.             this.getOwningTarget().getProject().setProperty("class-path",
  14.                     classPath);
  15.         } catch (Exception e) {
  16.             e.printStackTrace();
  17.         }
  18.     }
  19.     // 根据路径获得目录
  20.     private File dir(String path) throws Exception {
  21.         return dir(path, false);
  22.     }
  23.     private File dir(String path, boolean bCreate) throws Exception {
  24.         File dir = new File(path);
  25.         if (dir.exists()) {
  26.             if (!dir.isDirectory()) {
  27.                 throw new Exception(dir.getName() + "is not a directory !");
  28.             }
  29.         } else {
  30.             if (bCreate) { // 新建
  31.                 if (!dir.mkdirs()) {
  32.                     throw new Exception("can not create the directory /""
  33.                             + dir.getName() + "/"!");
  34.                 }
  35.             }
  36.         }
  37.         return dir;
  38.     }
  39.     // 生成classpath字符串
  40.     private void classPath(File dir) {
  41.         classPath(dir, lib);
  42.         classPath = classPath.trim();
  43.     }
  44.     private void classPath(File dir, String parentPath) {
  45.         // 处理目录
  46.         if (dir.isDirectory()) {
  47.             File[] subs = dir.listFiles();
  48.             for (int i = 0, len = subs.length; i < len; i++) {
  49.                 if (subs[i].isFile()) { // 文件
  50.                     String name = subs[i].getName();
  51.                     // 处理.jar文件
  52.                     if (name.length() > fileType.length()
  53.                             && fileType.equals(name.substring(name.length()
  54.                                     - fileType.length(), name.length()))) {
  55.                         classPath += parentPath + path(subs[i]) + " ";
  56.                         continue;
  57.                     }
  58.                 }
  59.                 if (subs[i].isDirectory()) { // 文件夹
  60.                     classPath(subs[i], parentPath + path(subs[i]));
  61.                 }
  62.             }
  63.         } else {
  64.             // 不是目录
  65.             System.out.println(dir.getPath() + dir.getName()
  66.                     + "is not a directory !");
  67.         }
  68.     }
  69.     // 文件路径
  70.     private String path(File f) {
  71.         return "/" + f.getName();
  72.     }
  73.     // 字符串 -- > 路径
  74.     @SuppressWarnings("unused")
  75.     private String path(String path) {
  76.         path = path.replaceAll("////", "/");
  77.         if (!"/".equals(path.substring(01))) {
  78.             path = "/" + path;
  79.         }
  80.         return path;
  81.     }
  82.     public void setLib(String lib) {
  83.         this.lib = lib;
  84.     }
  85. }

编译后打成jar包,拷贝到%ANT_HOME%/lib目录下,注意编译的时候需要导入ant的jar包,如果用ant打包就不需要导ant的jar包了,生成普通jar包的ant配置文件如下:

  1. <?xml version="1.0" encoding="GB2312" standalone="no"?>
  2. <project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
  3. <!-- 工程名,没有被引用,可以不改 -->
  4.       <property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
  5.       <property name="lib" value="lib"/> <!-- lib-->
  6.       <property name="src" value="src"/> <!-- src-->
  7.       <property name="tar" value="bin"/> <!-- bin -->
  8.       <property name="jar-file-name" value="${project-name}.jar"/>
  9.       <property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
  10.       <path id="Third-Part Lib">
  11.             <fileset dir="${lib}">
  12.                   <include name="**/*.jar"/>
  13.             </fileset>
  14.       </path>
  15.       <target description="Build file usage info (default task)" name="usage">
  16.             <echo message=" "/>
  17.             <echo message="  ${project-name} "/>
  18.             <echo message="-------------------------------------------------------"/>
  19.             <echo message="  Available Targets:"/>
  20.             <echo message="  compile    - Compiles the source code"/>
  21.             <echo message="  clean      - Delete class files and .jar file"/>
  22.             <echo message="  jar        - Generate an .jar for source code"/>
  23.             <echo message="  run        - Execute Main-Class"/>
  24.             <echo message="-------------------------------------------------------"/>
  25.       </target>
  26.       <target name="prepare">
  27.             <mkdir dir="${tar}"/>
  28.       </target>
  29.       <target name="clean">
  30.             <delete dir="${tar}"/>
  31.             <delete file="${jar-file-name}"/>
  32.       </target>
  33.     
  34.     <target name="copy-res">
  35.         <copy todir="${tar}">
  36.             <fileset dir="${src}">
  37.                 <exclude name="**/*.java"/>
  38.             </fileset>
  39.         </copy>
  40.     </target>
  41.       <target depends="clean,prepare,copy-res" name="compile">
  42.             <javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
  43.                   <classpath refid="Third-Part Lib"/> 
  44.             </javac>
  45.       </target>
  46.       <!--
  47.        <target name="run" depends="jar">
  48.             <java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
  49.       </target>
  50.       -->
  51.         <!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
  52.         <target depends="compile" name="run">
  53.             <java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
  54.                   <classpath refid="Third-Part Lib"/> 
  55.             </java>
  56.       </target>
  57.       <target depends="compile" name="jar">
  58.             <jar basedir="${tar}" destfile="${jar-file-name}">
  59.                   <manifest>
  60.                         <attribute name="Main-Class" value="${main-class}"/>
  61.                         <attribute name="Class-Path" value=""/>
  62.                   </manifest>
  63.             </jar>
  64.       </target>
  65. </project>

4.生成可执行jar包的ant配置文件如下:

  1. <?xml version="1.0" encoding="GB2312" standalone="no"?>
  2. <project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
  3. <!-- 工程名,没有被引用,可以不改 -->
  4.       <property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
  5.       <property name="lib" value="lib"/> <!-- lib-->
  6.       <property name="src" value="src"/> <!-- src-->
  7.       <property name="tar" value="bin"/> <!-- bin -->
  8.       <property name="jar-file-name" value="${project-name}.jar"/>
  9.       <property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
  10.       <path id="Third-Part Lib">
  11.             <fileset dir="${lib}">
  12.                   <include name="**/*.jar"/>
  13.             </fileset>
  14.       </path>
  15.       <target description="Build file usage info (default task)" name="usage">
  16.             <echo message=" "/>
  17.             <echo message="  ${project-name} "/>
  18.             <echo message="-------------------------------------------------------"/>
  19.             <echo message="  Available Targets:"/>
  20.             <echo message="  compile    - Compiles the source code"/>
  21.             <echo message="  clean      - Delete class files and .jar file"/>
  22.             <echo message="  jar        - Generate an .jar for source code"/>
  23.             <echo message="  run        - Execute Main-Class"/>
  24.             <echo message="-------------------------------------------------------"/>
  25.       </target>
  26.       <target name="prepare">
  27.             <mkdir dir="${tar}"/>
  28.       </target>
  29.       <target name="clean">
  30.             <delete dir="${tar}"/>
  31.             <delete file="${jar-file-name}"/>
  32.       </target>
  33.     
  34.     <target name="copy-res">
  35.         <copy todir="${tar}">
  36.             <fileset dir="${src}">
  37.                 <exclude name="**/*.java"/>
  38.             </fileset>
  39.         </copy>
  40.     </target>
  41.       <target depends="clean,prepare,copy-res" name="compile">
  42.             <javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
  43.                   <classpath refid="Third-Part Lib"/> 
  44.             </javac>
  45.       </target>
  46.       <!--
  47.        <target name="run" depends="jar">
  48.             <java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
  49.       </target>
  50.       -->
  51.         <!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
  52.         <target depends="compile" name="run">
  53.             <java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
  54.                   <classpath refid="Third-Part Lib"/> 
  55.             </java>
  56.       </target>
  57.       <!-- 自定义任务,创建并赋值变量class-path -->
  58.       <taskdef name="jarcp" classname="personal.lw.util.AntUtil"/>
  59.       <target name="class-path">
  60.         <jarcp lib="${lib}"/>
  61.       </target>
  62.       <target depends="compile,class-path" name="jar">
  63.             <jar basedir="${tar}" destfile="${jar-file-name}">
  64.                   <manifest>
  65.                         <attribute name="Main-Class" value="${main-class}"/>
  66.                         <attribute name="Class-Path" value="${class-path}"/>
  67.                   </manifest>
  68.             </jar>
  69.       </target>
  70. </project>

只比上一个多了一个自定义任务。

 

(完) ^_^

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值