How to run a .class file that is part of a package from cmd?(如何从 cmd 运行作为包一部分的 .class 文件?)
问题描述
当我将 .class 作为 package 的一部分并尝试从 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!");
}
}
然后是不起作用的代码:
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 the program via the command: 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
请记住,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 did cd C:/projects and HelloWorld.class is in C:/projects/com, then just type:
java com.HelloWorld
这篇关于如何从 cmd 运行作为包一部分的 .class 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 cmd 运行作为包一部分的 .class 文件?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
