First, the question
After compiling the. Java source file with the Javac command, you typically encounter the following or similar problems when you run a. class file with Java commands:
Error: The main class could not be found or could not be loaded Helloworld.class
Second, the settlement
The Javac command is used to compile the. Java source file. The. class file is produced directly in the. Java source file's sibling directory without the-D option, and the. class file is generated at the specified path and the file is in the directory corresponding to the package statement.
- When you specify the-D path option, A. class file with the same structure as the package declaration in the. Java file is generated under path. For example, if there is a package com.zsm.test in Helloworld.java, the javac-d path Helloworld.java is executed and the com/zsm/test/is generated under path Helloworld.class
- When there is no-d path option, the. class file is generated in the same directory as the. Java, regardless of whether there is a package declaration statement in the Helloworld.java. Although this is a simple approach, it is easier to make errors when executing the following Java commands because there is no directory corresponding to the package statement.
The Java command is used to execute the. class file, there are two ways to solve the problem of the main class that is not found or can not be loaded at the beginning , the key is that you need to precede the class name with the package declaration statement to run correctly.
- Generally we execute the Java package in the top level of the directory where the packages are located. The class name runs correctly. (If there is no package statement in Java, that is, under the default package, execute the Java class name command directly under the class directory)
- Another method is to use-CP to specify the directory at the top of the package, so that you do not have to cut into the directory to execute Java commands, that is, the JAVA-CP package in the top level of the directory. Class name . (if no package statement, then ibid.)
Iii. Summary
In summary, For. class files (with or without the-d path option), we have two ways to execute Java commands:
- A Java package is executed for the top-level directory of Packages . Class name , as assumed in the upper directory of COM, java Com.zsm.test.HelloWorld or Java Com/zsm/test/helloworld (Note that for the latter, if you switch to COM and then Java Zsm/test/helloworld is wrong)
- The other is to use the-CP option instead of the top-level directory of the package, which is the JAVA-CP package. The class name , as assumed currently in the COM directory, is JAVA-CP. /Com.zsm.test.HelloWorld can
If there is no package name in Java, execute the Java class name command directly in the directory where the. class is located.
Javac and Java Command usage issues (error or unable to load main class)