run Java in ubuntu

Running Java in Ubuntu can encounter issues as following:
1. NoClassDefFoundError issue
If you got NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: com/example/test/TestException
Caused by: java.lang.ClassNotFoundException: com.example.test.TestException
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: TestClass. Program will exit.

It is most properly that the java $CLASSPATH is not correctly set. Like setting the "Java build path" in eclipse.

You can check the $CLASSPATH first:
~$ echo $CLASSPATH
solution 1:
~$ export CLASSPATH=$CLASSPATH:/path/to/external/lib:/path/to/external/jar/file/example.jar
This is only available in your currently open terminal.

solution 2:
Add the CLASSPATH value in .profile. Open .profile in the user root folder and add the line below at the end of the file:
export CLASSPATH=$CLASSPATH:/path/to/external/lib:/path/to/external/jar/file/example.jar

solution 3:
Add the same line above in the shell file before running a java script if you use a shell file to call the java script.

And it is also possible that your java code is not compiled. When running java in shell script, the java script needs to be compiled first. Then the script needs to be run directly, a path specified java class can not be recognized. (e.g. ~$java path/folder/TestClass will also generate above wrong message)
~$ cd testclass/java/file/path
~$ javac TestClass.java
~$ cd testclass/java/file/path
~$ Java TestClass

2. different version problem
It is possible that you copy the compiled class from another project, or your local JDK and JRE are different versions. Eg. compile using JRE7 but run using JRE6. Use the following cmd to check the versions:
java -version
javac - version
If they are different, then you need to guarantee that the JRE should be higher than the JDK.

Comments

Popular posts from this blog

timestamp with 16, 13 and 10 digits to Qlik date

install postgreSQL in ubuntu 16.04

install ipython in Cloudera VM using pip