本文介绍了通过命令行运行java代码时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类

package chapter10;

public class CompilationTest {


  public static void main(String[] args) {
    System.out.println("HELLO WORLD");
  }

}

路径是

Test\src\chapter10\CompilationTest.java

我成功地将代码编译到同一个文件夹中,现在我已经

I successfully compiled the code into the same folder and now I have

Test\src\chapter10\CompilationTest.class

但是当我尝试从同一个文件夹运行时我收到此错误

However when I try to run from the same folder it I get this error

>java CompilationTest


Exception in thread "main" java.lang.NoClassDefFoundError: CompilationTest (wrong name: chapter10/CompilationTest)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: CompilationTest.  Program will exit.

当我使用

>java chapter10/PropertiesTest

Exception in thread "main" java.lang.NoClassDefFoundError: chapter10/PropertiesTest
Caused by: java.lang.ClassNotFoundException: chapter10.PropertiesTest
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: chapter10/PropertiesTest.  Program will exit.


推荐答案

该课程在第10章包。从父目录运行它:

The class is in the chapter10 package. Run it from the parent directory as:

java chapter10.CompilationTest

转到父级的原因是Java正在搜索其CLASSPATH,其中包含当前目录,用于 chapter10 包含 CompilationTest.class 文件的目录。您还可以将src目录的绝对路径添加到CLASSPATH以实现相同的效果:

The reason for going to the parent is that Java is searching its CLASSPATH, which includes the current directory, for a chapter10 directory containing a CompilationTest.class file. You could also add the src directory's absolute path to the CLASSPATH to achieve the same effect:

set CLASSPATH=C:\...\Test\src
java chapter10.CompilationTest

或者(显然这是更好的样式)将-cp或-classpath参数添加到java:

Or (apparently this is better style) add the -cp or -classpath argument to java:

java -cp "C:\...\Test\src" chapter10.CompilationTest

这篇关于通过命令行运行java代码时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:13