2012-04-15 122 views
7

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

<?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后面出现错误:package com.something does not exist ..我应该编辑哪些内容以使其正常工作?

确切错误:

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 
+0

您可以编辑您的问题向我们提供确切的错误? – Tom 2012-04-15 18:37:21

+0

我已经添加了确切的错误。 – Pajushka 2012-04-15 18:53:25

+0

你不能在一个普通的jar中轻松地包含外部库。你需要一些特殊的任务来完成这个任务。 – oers 2012-04-15 20:59:04

回答

4

你应该尝试,而不包括属性:

<fileset dir="lib" /> 

而且在罐子一部分,你包括类是这样的:

<zipgroupfileset includes="*.jar" dir="lib"/> 
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> 
1

你不能把外部库,装入瓶内,并期望类加载器使用这些罐子。不幸的是,这不被支持。

有蚂蚁的任务,如one jar,帮助您,创建一个jar文件,包含你所需要的一切。

该位是从background information of one jar

Unfortunately this is does not work. The Java Launcher$AppClassLoader does not know how to load classes from a Jar inside a Jar with this kind of Class-Path. Trying to use jar:file:jarname.jar!/commons-logging.jar also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.

Another approach is to unpack all dependent Jar files and repack them inside the jarname.jar file. This approach tends to be fragile and slow, and can suffer from duplicate resource issues.

其他替代:

  • jarjar:瓶瓶链接是一种实用工具,可以很容易地重新包装Java库和将它们嵌入到自己的分销
+0

不太准确,一些应用,如Hadoop的,例如,支持把罐子的约定在一个罐子里的lib目录和应用程序处理,让他们在classpath。 – 2013-05-05 07:38:30

+1

@DavidParks,但那是因为Hadoop使用自己的类加载器。所以这是应用程序特定的,不是官方jar定义的一部分。 – oers 2013-05-05 14:10:39

0

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

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