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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2864622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:51:35  来源:igfitidea点击:

How do I run .class files on windows from command line?

javawindowsterminal.class-file

提问by AndrejaKo

I'm trying to run .class file from command line. It works when I manually move to the directory it's stored in, but when I try something like this:

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

java C:\Peter\Michael\Lazarus\Main

it says it can't find the main class. Is there any solution to this other than making a .jar file (I know that .jar is the best solution, but at this moment isn't the one I'm looking for)?

它说它找不到主类。除了制作 .jar 文件之外,还有其他解决方案吗(我知道 .jar 是最好的解决方案,但目前不是我正在寻找的解决方案)?

采纳答案by Joachim Sauer

The Java application launcher(a.k.a java.exeor simply java) expects a class nameas its argument, so you can't pass it a file name (especially not one that includes a directory.

Java应用程序启动(又名java.exe或简单java)需要一个类名作为参数,所以你不能把它传递一个文件名(特别是没有一个包括目录。

You can tell it where to look for that class by using the -classpathoption (or its short form -cp) however:

您可以使用-classpath选项(或其缩写形式-cp)告诉它在哪里查找该类:

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

回答by kgiannakakis

Try this:

尝试这个:

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

You need to define the classpath.

您需要定义类路径。

回答by Michael Borgwardt

Assuming that Main.classdoes not have a package declaration:

假设Main.class没有包声明:

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

Java looks for classes in a "classpath", which can be set on the command line via the -cpoption.

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

回答by Arinomi

I just had the same issue, I tried running java hello.class, this is wrong.

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

The command should be java hello.

命令应该是java hello.

Do not include the file extension. It is looking for a class file, and will add the name on its own.

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

So running 'java hello.class' will tell it to go looking for 'hello.class.class' file.

所以运行 ' java hello.class' 会告诉它去寻找 ' hello.class.class' 文件。