Java: how to import a jar file from command line

JavaCommand LineJarClasspath

Java Problem Overview


I'm trying to call a class (main method) from command line (Windows) with Java.
The class imports other classes (other jars).

I always get "class not found exception" from a class that my main program imports.

Here's what I tried:

  • Add a CLASSPATH env. var with the path where the referenced lib resides (not working)

  • I tried with all these different parameters when calling "java -jar myjar.jar" from command line : "-classpath lib/", "-classpath ./lib/", "-classpath lib", "-cp lib/*", "-cp lib/\*", "-classpath lib/referenced-class.jar", "-classpath ./lib/referenced-class.jar" (lib is where the referenced jar resides)

  • I tried packaging all the referenced jar inside my jar where my main class resides...

  • And with all that, I also tried to specify the classes inside the Manifest file with: Class-path referenced-jar.jar and I also tried Class-path lib/referenced-jar.jar

Java Solutions


Solution 1 - Java

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

Solution 2 - Java

If you're running a jar file with java -jar, the -classpath argument is ignored. You need to set the classpath in the manifest file of your jar, like so:

> Class-Path: jar1-name jar2-name directory-name/jar3-name

See the Java tutorials: Adding Classes to the JAR File's Classpath.

Edit: I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the ':' after "Class-Path" like you showed, it would not work.

Solution 3 - Java

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

Solution 4 - Java

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrmugglesView Question on Stackoverflow
Solution 1 - JavaAdam PaynterView Answer on Stackoverflow
Solution 2 - JavaMichael MyersView Answer on Stackoverflow
Solution 3 - JavaartembView Answer on Stackoverflow
Solution 4 - JavacupakobView Answer on Stackoverflow