Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

java - How to run a .class file that is part of a package from cmd?

I keep getting errors when I make my .class part of a package and try to run it from cmd.

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!");
    }
}

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

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.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Suppose you did cd C:/projects and HelloWorld.class is in C:/projects/com, then just type:

java com.HelloWorld

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...