我有以下目录层次结构:
SigarTest src SigarTest .java files bin SigarTest .class files
这里,SigarTest是一个包名.根文件夹位于jdk的bin文件夹中.
从那里,我运行以下命令来创建我的项目的jar文件 –
./jar cfe temp.jar SigarTest.SigarMain SigarTest/bin/ tools.jar sigar.jar mongo-2.7.3.jar
其中tools.jar,mongo-2.7.3.jar和sigar.jar是必需的,并且与根目录(jdk的bin文件夹)位于同一文件夹中.然而,在运行它,我得到
ClassNotFoundException : SigarTest.SigarMain
我究竟做错了什么 ?
解决方法
使用
-C
dir option哪个
Temporarily changes directories (
cd
dir) during execution of thejar
command while processing the following inputfiles argument.
如果在问题中执行jar命令并列出temp.jar的内容,您将看到类似于以下内容的输出:
$rm -rf temp.jar $jar cfe temp.jar SigarTest.SigarMain SigarTest/bin/ tools.jar sigar.jar mongo-2.7.3.jar $jar tf temp.jar Meta-INF/ Meta-INF/MANIFEST.MF SigarTest/bin/ SigarTest/bin/SigarTest/ SigarTest/bin/SigarTest/SigarMain.class tools.jar sigar.jar mongo-2.7.3.jar $java -jar temp.jar Exception in thread "main" java.lang.NoClassDefFoundError: SigarTest/SigarMain Caused by: java.lang.ClassNotFoundException: SigarTest.SigarMain at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
请注意,在temp.jar中使用SigarTest / bin是不正确的.执行temp.jar会抛出ClassNotFoundException,因为SigarMain位于包SigarTest.bin.SigarTest中.现在考虑使用-Cir选项的以下jar命令:
$rm -rf temp.jar $jar cfe temp.jar SigarTest.SigarMain -C SigarTest/bin/ . tools.jar sigar.jar mongo-2.7.3.jar $jar tf temp.jar Meta-INF/ Meta-INF/MANIFEST.MF SigarTest/ SigarTest/SigarMain.class tools.jar sigar.jar mongo-2.7.3.jar $java -jar temp.jar
SigarMain位于正确的包中,执行temp.jar不会抛出ClassNotFoundException.