java运行时 报错 Error: Could not find or load main class test
报错 Error: Could not find or load main class test
可能原因:
1、没有配置环境变量
2、当java脚本中还有package定义时,需要创建package名字的文件夹,将.java和.class文件放到文件夹中,执行时也需要带上文件路径
配置JAVA_HOME和PATH
[root@node1 ~]# more .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
export JAVA_HOME=/home/dmdba/dmdbms/jdk
export PATH=$PATH:$HOME/bin:/home/dmdba/dmdbms/jdk/bin:/home/dmdba/dmdbms/jdk/jre/bin
[root@node1 ~]#source .bash_profile
java版本:
[root@node1 ~]# java -version
openjdk version "1.8.0_20"
OpenJDK Runtime Environment (build 1.8.0_20-b26)
OpenJDK 64-Bit Server VM (build 25.20-b23, mixed mode)
案例1
简单demo
[root@node1 ~]# more test.java
public class test{
public static void main(String args[]) {
System.out.println("hello World");
}
}
[root@node1 ~]# javac test.java
[root@node1 ~]# java test
Error: Could not find or load main class test
错误原因:没有配置CLASSPATH
[root@node1 ~]# pwd
/root
将test.class所在的路径加入到环境变量中
export CLASSPATH=/root
source .bash_profile 使环境变量生效
再次尝试运行,成功
[root@node1 ~]# java test
hello World
案例2
已经配置JAVA_HOME、PATH、CLASSPATCH
简单demo
[root@node1 ~]# more demo.java
package demo ;
public class demo{
public static void main(String args[]) {
System.out.println("hello World");
}
}
[root@node1 ~]# javac demo.java
[root@node1 ~]# java demo
Error: Could not find or load main class demo
错误原因:没有创建相应的文件夹
[root@node1 ~]# mkdir demo
[root@node1 ~]# mv demo.* ./demo
[root@node1 ~]# ll
total 20
drwxr-xr-x 2 root root 4096 Mar 31 06:44 demo
[root@node1 ~]# java demo.demo
hello World