开发者

Why am I getting a NoClassDefFoundError when I run a Java class file from the command line in Linux?

开发者 https://www.devze.com 2023-03-28 10:50 出处:网络
I am trying to run a test.class file from the linux command line.I compiled the file using javac test.java which produced the test.class file.When I run the command java test it throws a class not fou

I am trying to run a test.class file from the linux command line. I compiled the file using javac test.java which produced the test.class file. When I run the command java test it throws a class not found exception. I also tried specifying the package name with the same result. Here is the output, can anybody help? I believe my syntax is correct according to Google searches.

[root@localhost usr]# java test
Exception in thread "main" java.lang.NoClassDefFoundError: test (wrong name: testJava/test)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
        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$A开发者_Python百科ppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: test. Program will exit.


You need to compile your .java file with javac:

  javac MyFile.java

Then run the file using java

  java MyFile

If you're doing this and it still doesn't work, that means you need to make sure the file and the class name inside the file have the same name... so MyFile.java contains

  class MyFile
  {
     // ...
     public static void main(String[] args)
     {
        // ...
     }
     // ...
  }


Use java testJava.test from the parent directory of testJava


Assuming your class looks like this:

package javaTest;

public class test{
    public static void main(String[] a){
        System.out.println("Test");
    }
}

Then to compile and run the file, you basically do this:

$ ls
testJava
$ ls testJava
test.java
$ javac testJava/test.java
$ java testJava.test
Test

What this means is that you have to run the class with its fully qualified name, which includes the package name of the class.You also have to do it from the directory that conatins the root of your package. (Unless you specify the "root" directory with the -cp flag.)


I too had problem initially.

java -cp . Test

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号