Search code examples
javaruntime-error

ClassNotFoundException when trying to execute a jar


I'm working on a project that allows me to easily read and edit a certain type of file from a sort of terminal. It uses two java files, Main.java and Word.java, which have both been compiled into .class files.

In the folder with my com folder, there is also a bin folder containing a manifest file and another com folder containing the class files.

Here's a sort of visualisation of the file paths:

com vvv
    Main.java
    Word.java
bin vvv
    MANIFEST.MF
    com vvv
        Main.class
        Word.class

The manifest file looks like this:

Manifest-Version: 1.0
Class-Path: .
Main-Class: com.Main
Created-By: 19.0.2 (Oracle Corporation)

To compile it, I use the Visual Studio Code terminal and use the command jar cvfm DictionaryParser.jar bin/MANIFEST.MF bin/com/Main.class bin/com/Word.class

This successfully compiles it into a .jar file. However, whenever I run this jar file, using the command java -jar DictionaryParser.jar, it gives me this error.

Error: Could not find or load main class com.Main
Caused by: java.lang.ClassNotFoundException: com.Main

No matter what I do, this error keeps coming up. Java cmd commands in general are really confusing to me, but I just don't get what I'm doing wrong here. Any ideas? Am I just making a stupid mistake? Keep in mind I don't have much experience with Java compared to other programming languages, especially the JVM.


Solution

  • You're putting your classes in the wrong folder. Here is an example.

    This is the incorrect way.

    jar cf Test.jar junk/com/Broken.class

    Which results in:

    $jar tf Test.jar 
    META-INF/
    META-INF/MANIFEST.MF
    junk/com/Broken.class
    
    

    See the folder structure is incorrect. The package should be the root folder.

    The correct way.

    jar cf Test.jar -C junk com/Broken.class

    Then the jar contains:

    $jar tf Test.jar 
    META-INF/
    META-INF/MANIFEST.MF
    com/Broken.class