我正在尝试从命令行运行.class文件。当我手动切换到存储它的目录时,它可以正常工作,但是当我尝试像这样运行:
java C:\Peter\Michael\Lazarus\Main
它显示找不到主类。除了制作 .jar 文件之外,是否有其他解决方案(我知道 .jar 是最佳解决方案,但此时不是我要寻找的解决方案)?
我正在尝试从命令行运行.class文件。当我手动切换到存储它的目录时,它可以正常工作,但是当我尝试像这样运行:
java C:\Peter\Michael\Lazarus\Main
它显示找不到主类。除了制作 .jar 文件之外,是否有其他解决方案(我知道 .jar 是最佳解决方案,但此时不是我要寻找的解决方案)?
Java应用程序启动器(也称为java.exe
或简单地java
)支持最多四种不同的方式来指定要启动的内容(取决于您使用的Java版本)。
Specifying a class name is the most basic way. Note that the class name is different from the file name.
java -cp path/to/classFiles/ mypackage.Main
Here we start the class mypackage.Main
and use the -cp
switch to specify the classpath which is used to find the class (the full path to the class mypackage.Main
will be path/to/classFiles/mypackage/Main.class
.
Starting a jar file.
java -jar myJar.jar
This puts the jar itself and anything specified on its Class-Path
entry on the class path and starts the class indicated via the Main-Class
entry. Note that in this case you can not specify any additional class path entries (they will be silently ignored).
Java 9 introduced modules and with that it introduce a way to launch a specific module in a way similar to how option #2 works (either by starting that modules dedicated main class or by starting a user-specified class within that module):
java --module my.module
Java 11 introduces support for Single-File Source Code Programs, which makes it very easy to execute Java programs that fit into a single source file. It even does the compile step for you:
java MyMain.java
This option can be useful for experimenting with Java for the first time, but quickly reaches its limits as it will not allow you to access classes that are defined in another source file (unless you compile them separately and put them on the classpath, which defeats the ease of use of this method and means you should probably switch back to option #1 in that case).
This feature was developed as JEP 330 and is still sometimes referred to as such.
针对您的特定情况,您将使用选项#1,并通过使用-classpath
选项(或其简写形式-cp
)告诉java
在哪里查找该类:
java -classpath C:\Peter\Michael\Lazarus\ Main
Main.java
文件中(并且它在相同的目录中),那么您可以使用选项#4,跳过编译步骤,直接编译并执行它。java c:\Peter\Michael\Lazarus\Main.java
假设Main.class
没有包声明:
java -cp C:\Peter\Michael\Lazarus\ Main
Java会在“类路径”中寻找类,可以通过命令行选项-cp
来设置类路径。
我遇到了同样的问题,我尝试运行java hello.class
,这是错误的。
正确的命令应该是java hello
。
不要包括文件扩展名。它正在寻找一个类文件,并将自动添加名称。
因此,运行'java hello.class
'会让它去寻找'hello.class.class
'文件。
试试这个:
java -cp C:\Peter\Michael\Lazarus Main
您需要定义类路径。