如何在Windows命令行上运行.class文件?

24

我正在尝试从命令行运行.class文件。当我手动切换到存储它的目录时,它可以正常工作,但是当我尝试像这样运行:

java C:\Peter\Michael\Lazarus\Main

它显示找不到主类。除了制作 .jar 文件之外,是否有其他解决方案(我知道 .jar 是最佳解决方案,但此时不是我要寻找的解决方案)?

4个回答

36

Java应用程序启动器(也称为java.exe或简单地java)支持最多四种不同的方式来指定要启动的内容(取决于您使用的Java版本)。

  1. 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.

  2. 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).

  3. 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
    
  4. 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

哇塞!Java只用了11个版本就可以在简单的方式下运行一个简单的程序。现在说正经的,它非常适合快速原型设计、测试新功能,并且对于Java新手(比如我)来说非常易学易用。 - Leonardo Maffei

11

假设Main.class没有包声明:

java -cp C:\Peter\Michael\Lazarus\  Main

Java会在“类路径”中寻找类,可以通过命令行选项-cp来设置类路径。


8

我遇到了同样的问题,我尝试运行java hello.class,这是错误的。

正确的命令应该是java hello

不要包括文件扩展名。它正在寻找一个类文件,并将自动添加名称。

因此,运行'java hello.class'会让它去寻找'hello.class.class'文件。


4

试试这个:

java -cp C:\Peter\Michael\Lazarus Main

您需要定义类路径。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接