Why does my .jar file raise exceptions even if my program runs without exceptions in Eclipse?

余生长醉 提交于 2019-12-24 04:43:04

问题


I am new to Java and learning how to export applications to .jar files. I made a simple Java application in Eclipse with a few classes based on the tutorial from Eclipse and Java for Total Beginners.

When I run my application via Run -> Run in Eclipse, my application runs without exceptions. However, when I got to File -> Export and export my application into a .jar file and then execute

java myLibrary.jar

in my Mac terminal, I get this output from standard error.

Exception in thread "main" java.lang.NoClassDefFoundError: myLibrary/jar

Caused by: java.lang.ClassNotFoundException: myLibrary.jar
    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)

What does this mean? How am I missing classes? I tried checking and unchecking items to export. For instance, I tried including my JUnit tests to no avail.


回答1:


In the terminal go to the directory that contains all your class files.

jar cmf MANIFEST.MF myLibrary.jar *

Then if the jar is created successfully you can run it by:

java -jar myLibrary.jar

The MANIFEST.MF file should contain at the very least:

Main-Class: myLibrary

Where myLibrary is the class that contains your main function.




回答2:


when you run java without arguments it will print:

Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

use the -jar to run your jar file.

You would also need to indicate what class to run. You can do so in your manifest (you would use the Main-Class header). You can read more about it here: http://docs.oracle.com/javase/tutorial/deployment/jar/run.html




回答3:


In eclipse, Right click on your project -> Click on export -> Java -> Jar file -> Select the source folders (Defaults should do fine in most cases). Give the location of the jar file. Go to the last page of the wizard, in the "Select the class of the application entry point:", Select the java class file which has main.



来源:https://stackoverflow.com/questions/10588313/why-does-my-jar-file-raise-exceptions-even-if-my-program-runs-without-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!