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 jav
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.
Run the program from the parent directory of the com directory.
java com.HelloWorld
Suppose you did cd C:/projects
and HelloWorld.class
is in C:/projects/com
, then just type:
java com.HelloWorld
Create a folder named com
under Java folder and put the HelloWorld.java
into com
folder. Then run again javac
and java
.
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.
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