On CentOS 7.2 Linux I have successfully downloaded and installed Oracle Java with:
# rpm -Uvh jdk-8u91-linux-x64.rpm
Also there is already OpenJDK installed:
# rpm -qa | grep -i jdk
java-1.8.0-openjdk-headless-1.8.0.91-0.b14.el7_2.x86_64
java-1.8.0-openjdk-1.8.0.91-0.b14.el7_2.x86_64
jdk1.8.0_91-1.8.0_91-fcs.x86_64
I can switch between the 2 using this command:
# alternatives --config java
There are 2 programs which provide 'java'.
Selection Command
-----------------------------------------------
* 1 /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.91-0.b14.el7_2.x86_64/jre/bin/java
+ 2 /usr/java/jdk1.8.0_91/jre/bin/java
Enter to keep the current selection[+], or type selection number:
And see the version with:
# java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
# javac -version
javac 1.8.0_91
Now to my problem please –
I create a simple java file named TheClassName.java
:
package thepackagename;
public class TheClassName {
public static final void main(String[] args) {
System.out.println("Hello World!");
}
}
After successfully compiling it with javac TheClassName.java
(which produces TheClassName.class
file in the same dir) I unfortunately can not run it:
# java -cp . thepackagename.TheClassName
Error: Could not find or load main class thepackagename.TheClassName
Here another try:
# export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.91-0.b14.el7_2.x86_64/jre
# $JAVA_HOME/bin/java -cp . thepackagename.TheClassName
Error: Could not find or load main class thepackagename.TheClassName
Setting another environment variable does not help either:
# export CLASSPATH=.
Similar command on Windows 7 works well and I have tried copying the TheClassName.class
file from there to Linux too.
Please help and please do not suggest marking this question as duplicate, because as you see above, I have already tried most of the suggestions.
The SELINUX is off (SELINUX=disabled
) and the server was installed few weeks ago, serving (without errors) as LAMP with MySQL/PostgreSQL/Apache/WordPress.
UPDATE:
Yes, I had to move the class file under thepackagename
dir and then it works:
# ls thepackagename
TheClassName.class
# java -cp . thepackagename.TheClassName
Hello World!
I can even create a test.jar
file and it still works now:
# zip -r test.jar thepackagename
adding: thepackagename/ (stored 0%)
adding: thepackagename/TheClassName.class (deflated 31%)
# java -cp test.jar thepackagename.TheClassName
Hello World!
Best Answer
If the class is in a package:
Then calling it from the wrong directory results in:
It must be called with its fully-qualified name:
And this command must be called from the same directory in which the
thepackagename
directory exists. This means you have to create a new directory calledthepackagename
and moveTheClassName.class
into it, then run the above command from the parent directory of thethepackagename
directory.