【发布时间】:2014-11-26 13:02:53
【问题描述】:
我的项目布局:
.
├── bin
│ ├── build
│ │ └── hello.jar
│ │── classes
│ └── helloworld
│ └── Main.class
├── build.xml
├── lib
│ └── postgresql.jar
└── src
└── helloworld
└── Main.java
构建.xml
<project>
<property name="class_dir" value="bin/classes"/>
<property name="src_dir" value="src"/>
<property name="build_dir" value="bin/build"/>
<property name="jar_name" value="hello.jar"/>
<property name="lib_dir" value="lib"/>
<target name="clean">
<delete dir="${class_dir}"/>
<delete dir="${build_dir}"/>
</target>
<target name="compile">
<mkdir dir="${class_dir}"/>
<javac includeantruntime="false" srcdir="${src_dir}" destdir="${class_dir}"/>
</target>
<target name="jar">
<mkdir dir="${build_dir}"/>
<jar destfile="${build_dir}/${jar_name}" basedir="${class_dir}">
<manifest>
<attribute name="Main-Class" value="helloworld.Main"/>
</manifest>
</jar>
</target>
<target name="run" >
<java jar="${build_dir}/${jar_name}" fork="true" failonerror="true">
<classpath>
<pathelement location="${lib_dir}/postgresql.jar"/>
</classpath>
</java>
</target>
执行ant run时的错误:
run:
[java] java.lang.ClassNotFoundException: org.postgresql.Driver
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[java] at java.lang.Class.forName0(Native Method)
[java] at java.lang.Class.forName(Class.java:259)
[java] at helloworld.Main.main(Unknown Source)
[java] Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5430/hello_world
[java] at java.sql.DriverManager.getConnection(DriverManager.java:689)
[java] at java.sql.DriverManager.getConnection(DriverManager.java:247)
[java] at helloworld.Main.main(Unknown Source)
在执行 jar 文件时甚至可以指定这样的类路径吗? (我已经回显了类路径,它看起来很好。)
编辑:
根据http://www.coderanch.com/t/108841/tools/Ant-Compile-time-runtime-classpath,我想要实现的目标是不可能的。
【问题讨论】:
-
这个程序在 Ant 之外运行正常吗?
-
如果我使用
-cp CLASSPATH选项,只要它没有被打包成 jar 即java -cp CLASSPATH -jar myjar.jar不起作用,我就可以运行它。 -
看起来你的 classpath xml 元素可能在 java 标签之外。
-
哎呀,你是对的。不幸的是,我在更正后仍然收到错误。
-
当您点击 ant run 时,您可能会回显 lib_dir。我在这里没有想法了。另外,请注意,如果您使用 java -jar,如果您还没有这样做,您仍然需要指定外部 jar 的路径。