Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is a class path in java?

Tags:

java

classpath

I wrote a program that works on my laptop perfectly, but I really want it to work on a server that I have. Using NetBeans, I've clean and built the project. I copied the contents of the folder dist on my server but I cannot seem to get to work by using command

java -jar nameOfFile.jar

I get the error

java.lang.NoClassDefFoundError: org/....

I have been doing some reading and from what I gather is that I need to pretty much specify where the libraries that I've used are located. Well they are located in a subfolder called lib.

Question:

So what would I need to do in order to be able to run my jar?

like image 467
user1198778 Avatar asked Mar 08 '14 05:03

user1198778


People also ask

What are class paths in Java?

The Java class path tells a Java compiler or Java Virtual Machine (JVM) where to look for Java classes and libraries needed to compile or run Java programs. Where to set it. There are two ways to set the class path: with an environment variable or with a command-line option of the JVM.

What is path and class path in Java?

PATH is used by CMD prompt to find binary files. CLASSPATH is used by the compiler and JVM to find library files.

How do I find my Java classpath?

Now to check the value of Java classpath in windows type "echo %CLASSPATH" in your DOS command prompt and it will show you the value of the directory which is included in CLASSPATH.


2 Answers

CLASSPATH is an environment variable that helps us to educate the Java Virtual Machine from where it will start searching for .class files.

We should store the root of the package hierarchies in the CLASSPATH environment variables.

In case of adding or using jar libraries in our project, we should put the location of the jar file in the CLASSPATH environment variable.

Example: If we are using jdbc mysql jar file in our java project, We have to update the location of the mysql jar file in the CLASSPATH environment variable. if our mysql.jar is in c:\driver\mysql.jar then

We can set the classpath through DOS in Windows

set CLASSPATH=%CLASSPATH%;c:\driver\mysql.jar 

In Linux we can do

export CLASSPATH=$CLASSPATH:[path of the jar]

Hope it helps!

like image 178
Chinmay Patel Avatar answered Sep 29 '22 17:09

Chinmay Patel


Try that:

java -classpath "$CLASSPATH:nameOfFile.jar:lib/*" path.to.your.MainClass

What this does is setting the classpath to the value of $CLASSPATH, plus nameOfFile.jar, plus all the .jar files in lib/.

like image 23
Florent Bayle Avatar answered Sep 29 '22 17:09

Florent Bayle