Java running a program at command prompt: could not find or load main class

允我心安 提交于 2019-12-10 15:59:36

问题


I am trying to learn how to compile and run using only command lines in Windows. Here is the tree of the directories starting from the root:

D:
 ActivityOne
     - classes
         - com
           -wat
             -sampleapp
                -students
                    StudentE.class
                 StudentMasterList.class (Main)
     - src
         -com
           -wat
             -sampleapp
                -students
                    StudentE.java
                 StudentMasterList.java (Main)

The thing is that I am now confused as to how to run the program. I tried two things, where both returned different errors.

1st try:

java -classpath classes StudentMasterList

returned:

Error: Could not find or load main class StudentMasterList

2nd try:

java -classpath classes/com/wat/sampleapp StudentMasterList

returned:

Exception in thread "main" java.lang.NoClassDefFoundError: StudentMasterList (wrongname: com/wat/sam
pleapp/StudentMasterList)
at java.lang.ClassLoader.defineClass1(Native Method)
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$100(Unknown Source)
at java.net.URLClassLoader$1.run(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)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

I got confused after the next tries, any help on how i should run the main class?

Update: I should run all my commands at the ActivityOne level.


回答1:


The correct way is

java -classpath D:\ActivityOne\classes com.wat.sampleapp.StudentMasterList

In other words, you add the top-level directory to the classpath, and then use the fully-qualified name of your Java class.



来源:https://stackoverflow.com/questions/17388287/java-running-a-program-at-command-prompt-could-not-find-or-load-main-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!