如何从cmd运行作为包的一部分的.class文件? [英] How to run a .class file that is part of a package from cmd?
问题描述
当我把我的类作为包的一部分并尝试从cmd运行时,我一直收到错误。
I keep getting errors when I make my class part of a package and try to run it from cmd.
这里的代码在使用javac然后java :
Here's the code that works after using javac and then java:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
p>
and then the code that does not work:
package com;
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
在尝试运行java HelloWorld :
giving me this error after trying to run "java HelloWorld":
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong nam
e: com/HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
这是我试过的到目前为止:
Here's what I've tried doing so far:
java -cp . HelloWorld
java -cp . com.HelloWorld
java -cp . com/HelloWorld
java HelloWorld
java com.HelloWorld
java com/HelloWorld
$ b b
请记住,javac返回没有错误,只是删除package com;解决问题。有时在其他情况下,我得到一个错误,说无法找到主类文件或沿着这些行的东西。
Keep in mind that javac returns with no errors and that simply removing "package com;" solves the problem. Sometimes in other scenarios I get an error that says the main class file cannot be found or something along those lines.
我做错了什么?
推荐答案
假设你已经cd'到C:/ projects和HelloWorld.class在C:/ projects / com,只需键入
Suppose you've cd'd to C:/projects and HelloWorld.class is in C:/projects/com, just type
java com.HelloWorld
这篇关于如何从cmd运行作为包的一部分的.class文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!