Ant包括外部.jar

时间:2012-04-15 18:31:02

标签: java ant jar build.xml

我想在我的java项目中包含外部jar。我正在使用蚂蚁。外部.jar位于文件夹lib中。我的build.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <path id="classpath">
        <fileset dir="lib" includes="**/*.jar"/>
    </path>

    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build"/>
        <javac srcdir="src" destdir="build" classpathref="classpath" />
    </target>

    <target name="jar">
        <mkdir dir="trash"/>
        <jar destfile="trash/test.jar" basedir="build">
            <zipgroupfileset dir="lib" includes="**/*.jar"/>
            <manifest>
                <attribute name="Main-Class" value="com.Test"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="trash/test.jar" fork="true"/>
    </target>
</project>

但它不起作用。当我想从外部.jar导入一些东西时,命令ant compile之后出现错误:包com.something不存在。我应该编辑什么才能使它工作?

确切错误:

  Compiling 23 source files to xy/build
  xy/src/com/Test.java:5: package com.thoughtworks.xstream does not exist
  import com.thoughtworks.xstream.*;
  ^
  1 error

4 个答案:

答案 0 :(得分:4)

您应该尝试不使用includes属性:

<fileset dir="lib" />

在jar部分你包括这样的类:

<zipgroupfileset includes="*.jar" dir="lib"/>

答案 1 :(得分:1)

您不能将外部库放入jar中,并期望类加载器使用这些jar。不幸的是,这不受支持。

one jar这样的ant任务可以帮助您创建一个包含所需内容的jar文件。

此位来自background information of one jar

  

不幸的是,这不起作用。 Java Launcher $ AppClassLoader   我不知道如何从Jar内的Jar中加载类   类路径。试着用   jar:file:jarname.jar!/commons-logging.jar也引领了一个死胡同。   这种方法只有在你安装(即分散)时才有效   支持Jar文件到jarname.jar文件所在的目录   安装。

     

另一种方法是解压缩所有相关的Jar文件并重新打包它们   在jarname.jar文件中。这种方法往往很脆弱   慢,并且可能会遇到重复的资源问题。

其他选择:

  • jarjar:Jar Jar Links是一个实用程序,可以轻松地重新打包Java库并将它们嵌入到您自己的发行版中

答案 2 :(得分:0)

我还使用ant在我的JAR中包含了许多依赖JAR。我的编译任务看起来像这样。也许类似的东西对你有用。

<target name="compile" depends="init">
   <javac srcdir="${src}" destdir="${build}" includeantruntime="false">
    <classpath>
      <pathelement path="${classpath}" />
      <fileset dir="${deps}">
         <include name="**/*.jar"/>
      </fileset>
    </classpath>
  </javac>
  <copy todir="${build}">
    <fileset dir="${src}" excludes="**/*.java"/>
  </copy>
</target>

答案 3 :(得分:0)

有时你可以直接使用jar内容,只需解压缩

        <unzip src="/Developer-Java/mysql-connector-java/mysql-connector-java-5.1.22-bin.jar" dest="${build_dir}" />
相关问题