[英]Why am I getting a NoClassDefFoundError when I run a Java class file from the command line in Linux?
I am trying to run a test.class
file from the linux command line.我正在尝试从 linux 命令行运行
test.class
文件。 I compiled the file using javac test.java
which produced the test.class
file.我使用
javac test.java
编译了文件,生成了test.class
文件。 When I run the command java test
it throws a class not found exception.当我运行命令
java test
时,它会引发 class 未找到异常。 I also tried specifying the package name with the same result.我还尝试使用相同的结果指定 package 名称。 Here is the output, can anybody help?
这是output,有人可以帮忙吗? 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$AppClassLoader.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 编译您的.java 文件:
javac MyFile.java
Then run the file using java然后使用 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.java 包含
class MyFile
{
// ...
public static void main(String[] args)
{
// ...
}
// ...
}
Use java testJava.test
from the parent directory of testJava使用
java testJava.test
父目录下的 java testJava.test
Assuming your class looks like this:假设您的 class 看起来像这样:
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. 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.) (除非您使用
-cp
标志指定“根”目录。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.