user1407668
user1407668

Reputation: 617

java.lang.ClassNotFoundException while executing a class file from inside a jar

I created a jar file in windows & copied it to linux and tried to execute with the following command:

java -jar Test.jar com.dcat2.messaging.datatransfer.Test

I am getting an exception as follows:

Exception in thread "main" java.lang.NoClassDefFoundError: Test
Caused by: java.lang.ClassNotFoundException: Test
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: Test. Program will exit.

I am executing this command in the same location where i have the jar file.

Here is my java code:

package com.dcat2.messaging.datatransfer;

public class Test {
public static void main(String[] args) {
    System.out.println("Test App : " + args[0]);

}
}

The jar -tf command's output is as follows:

jar -tf Test.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/dcat2/
com/dcat2/messaging/
com/dcat2/messaging/datatransfer/
com/dcat2/messaging/datatransfer/Test.class

Can anyone help please?

Upvotes: 0

Views: 5603

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

java -cp Test.jar com.dcat2.messaging.datatransfer.Test

The -jar option launches the class that is indicated as the main class in the manifest of the jar file (and which must be the Test class, in the default package, in your case).

The -cp option sets the classpath to use for the app which, in this case, only contains your test jar.

Upvotes: 1

Related Questions