How to run a .class file that is part of a package from cmd?
Asked Answered
B

13

42

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?

Balfore answered 9/8, 2013 at 3:46 Comment(5)
Where does HelloWord live? Does it live in the com/ directory?Nevski
I think you do not have the folder "com".Hackworth
It lives in a directory created by me C:\java in which are located HelloWorld.java and HelloWorld.classBalfore
Let me try renaming the directory to the package name and see what happensBalfore
The problem is now resolved. Turns out that I was using the java command from within the package folder and I had to cd backwards for it to work.Balfore
S
38

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

java com.HelloWorld
Stealer answered 9/8, 2013 at 3:54 Comment(4)
The file now resides in C:\com. When I try out your command it says:Balfore
Error: COuld not find or load main class com.HelloWorldBalfore
At that point you must be cd'd into C:\, not C:\com. In other words, you need to try running it from outside of the package directory.Stealer
But why should one run from outside. How can one run from inside?Harriman
N
17

Packages are directly related to the expected directory location of the file.

That is, if you have a source file with the package directive of com, it is expected that the file will live in the com directory.

In your HelloWorld example, it would be expected that the HelloWorld.java file would be stored in the com directory, like com\HelloWorld.java

When you compile the file, it will create a class file called HelloWorld.class in the com directory, like com\HelloWorld.class

This way, when Java goes looking for the com.HelloWorld class, it would actually be searching it's class path and appending com\HelloWorld.class to it until it finds your class file or runs out of class path

Example

So, I copied your HelloWorld.java (with package) example to C:\java\com\HelloWord.java

From the command line, I changed to the C:\java directory...

C:\java>dir com
 Volume in drive C is OS
 Volume Serial Number is ####-####

 Directory of C:\java\com

09/08/2013  01:55 PM    <DIR>          .
09/08/2013  01:55 PM    <DIR>          ..
09/08/2013  01:55 PM               135 HelloWorld.java

Then I compiled the HelloWorld.java

C:\java>javac com\HelloWorld.java

Then I ran it...

C:\java>java com.HelloWorld
Hello World!

You might like to have a read through Packages tutorial

Nevski answered 9/8, 2013 at 3:54 Comment(3)
The file now lives in C:\com. The problem is the same when I use "java HelloWorld" and when I try "java com.HelloWorld" like @sbat suggested it cannot find or load the main class.Balfore
Okay. Did you try my example? You could replace C:\java\com for C:\com because, as I demonstrated, it works fine...Nevski
there is a typo. You meant to say live but said lifeDerian
A
4

The syntax is:

java -classpath /path/to/package-folder <packageName>.<MainClassName>

So you may try: java com.HelloWorld which would expect com/HelloWorld.class file to be present as classpath by default points to the current directory (if not specified).

In case you're in different folder, try specifying classpath:

$ CLASSPATH=/path/to/package-folder/ java com.HelloWorld
Hello World!
$ java -cp /path/to/package-folder/ com.HelloWorld
Hello World!
$ cd /path/to/package-folder/ && java com.HelloWorld
Hello World!

For further explanation, check: How do I run Java .class files?

Adalineadall answered 10/12, 2015 at 23:3 Comment(0)
W
3

Run the program from the parent directory of the com directory.

java com.HelloWorld
Weiland answered 9/8, 2013 at 3:56 Comment(0)
I
3

When you compile the java code, use -d, in your case, it would be

javac -d . com.HelloWorld.java

After the above command, java compiler generate a folder named "com", under the "com" folder, you will see your HelloWorld.class

Then under the same folder as you run javac, run the following command

java com.HelloWorld
Immoderation answered 3/5, 2017 at 17:40 Comment(1)
For me worked: javac -d HelloWord.java and then -> java com.HelloWorldViral
A
3

Suppose the file locates at C:/projects/com/HelloWorld and you can try the following ways.

1.java -cp c:/projects com.HelloWorld

2.cd c:/projects
 java com.HelloWorld
(The example 2 is not working in many situation,such as java process.)

if there is no package declaration and there will be a little change.

1.java -cp c:/projects/com HelloWorld

2.cd c:/projects/com
 java HelloWorld
(It's not good with the same reason.)

alternatively,relative path will be ok but has some risk. Last remember put the class file in end of cmd.

Ambulance answered 7/6, 2017 at 7:7 Comment(0)
H
1

Create a folder named com under Java folder and put the HelloWorld.java into com folder. Then run again javac and java.

Hackworth answered 9/8, 2013 at 4:4 Comment(0)
J
1

There could be such a problem, when you are executing 'java' command directly from folder of your '*.class' files. This command should be executed from project 'parent' directory. All is well explained in the following article:

http://javarevisited.blogspot.de/2015/04/error-could-not-find-or-load-main-class-helloworld-java.html

Johnstone answered 8/3, 2017 at 10:53 Comment(0)
G
0

Try to use absolute directory or put your HelloWorld.class into ..\last_directory\com

1. java -cp .......\last_directory com.HelloWorld
2. java -cp .......\last_directory HelloWorld(with created com)
Grig answered 9/8, 2013 at 3:55 Comment(0)
S
0

You do not need a -cp flag while running a java class , -cp needed while running a class or a main program from a binary (jar) file. While running a main program from a command line you need to make sure you have the class in the same folder structure as package name in the java file, ex.

home/user/foo java com.test.className   

here classNmae class file and exist under home/user/foo/com/test

hope it helps.

Saltzman answered 2/1, 2017 at 4:50 Comment(0)
H
0

Simple Solution in Linux, same principle:

Say, the File is /work/packageName/file.java, with a first line:

package packageName;

Under the working directory /work/packageName/*:

javac file.java will not work, as long as file.java contain any reference to other files in that package. The solution is to use this:

javac --class-path  ../  file.java

Or go 1 level up to /work/* and run:

javac  ./packageName/Member.java

Or simply use java instead of javac to execute.

Hinckley answered 18/5, 2020 at 9:11 Comment(0)
P
0

if java file contains "project", descent and run java package.class (package name = parent dir name) else run it from same directory (I'd say normally) #beware empty spaces, and such, not perfect ...


package=""
package=`cat $java_file | grep package | awk '{print $2}' | sed 's/;//g'`
path_p="."
[[ ! -z $package ]] && class_p="$package.$class" && path_p=".."   # ;)

cd $path_p
java $class_p
Parathyroid answered 13/11, 2022 at 20:30 Comment(0)
S
-2

You should compile it first by typing this command in CMD, for exemple your file is in c:\ directory :

C:\com>javac HelloWorld.java

After that you can run the result by typing:

c:\com>java HelloWorld
Sabulous answered 9/8, 2013 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.