0

I'm trying to create a jar file for one of my Java files. However, once I create it and try to run it, I get a java.lang.NoClassDefFoundError.

I did the following to create the jar. The file is Worker.java and it's in src/beatDB.

jar cfm Worker.jar Manifest.txt src/beatDB

My Manifest.txt file is just

Main-Class: Main-Class: beatDB.Worker \n (with a new line afterwords)

When I run java -jar Worker.jar, I get this error.

Exception in thread "main" java.lang.NoClassDefFoundError:
beatDB/Worker
Caused by: java.lang.ClassNotFoundException: beatDB.Worker
    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)

However if I run java beatDB/Worker, the file runs fine.

Does anyone know how to fix this problem?

user1998511
  • 455
  • 1
  • 8
  • 21

1 Answers1

1

You should jar the manifest along with the .class files, not the .java files.

.java files contain the source code.

.class files contain the compiled code. For Java it is called byte code.

You want the package structure of your classes to be reflected in your jar file. If you have an Animal class under com.example, then your jar file should contain com/example/Animal.class

See How to create jar file with package structure? for the proper jar file package structure.

Community
  • 1
  • 1
Tarik
  • 10,810
  • 2
  • 26
  • 40
  • When I do ```jar cfm Worker.jar Manifest.txt src/beatDB/*.class```, I still get the same error when running the jar – user1998511 Apr 06 '15 at 19:46
  • Are you sure the .class files are under the src folder? – Tarik Apr 06 '15 at 19:54
  • Positive. I did ```javac src/beatDB/*.java``` before creating the jar file to compile all the java files. They also appeared in src/beatDB when I looked. – user1998511 Apr 06 '15 at 19:58
  • jar cfm Worker.jar Manifest.txt src – Tarik Apr 06 '15 at 20:00
  • You want the package structure of your classes to be reflected in your jar file. If you have an Animal class under com.example, then your jar file should contain com/example/Animal.class – Tarik Apr 06 '15 at 20:02
  • By jaring your files with src as the argument, tje proper folder structure should be created albeit the extra .java files that are redundant. The solution is to create a bin folder structure that contains the class files only. – Tarik Apr 06 '15 at 20:06