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

大憨熊 提交于 2019-11-27 05:49:02

问题


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:

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)?


回答1:


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

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

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



回答2:


Assuming that Main.class does not have a package declaration:

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

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




回答3:


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

The command should be 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.




回答4:


Try this:

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

You need to define the classpath.



来源:https://stackoverflow.com/questions/2864622/how-do-i-run-class-files-on-windows-from-command-line

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