Execute jar file with multiple classpath libraries from command prompt

Praneeth picture Praneeth · Oct 22, 2012 · Viewed 146.6k times · Source

I have a Maven project which generates a jar file and copies all dependencies to target/lib folder. I want to execute this project on client's machine (windows). So, I copied myproject.jar to C:\xyz folder and all dependencies to C:\xyz\lib folder. How do I execute this project from client's command prompt? I tried to use java -cp lib\*.jar -jar myproject.jar from C:\xyz folder but it throws following error.

Exception in thread "main" java.lang.NoClassDefFoundError: lib\commons-codec-1/3/jar
Caused by: java.lang.ClassNotFoundException: lib\commons-codec-1.3.jar
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: lib\commons-codec-1.3.jar.  Program will exit.

I think if I specify all dependencies in classpath (like java -cp lib\dep1.jar;dep2.jar), it will get rid of the problem but I don't want to do this as I have 40 libraries already and it might grow in future releases. Is there a better way to do this?

Answer

Sualeh Fatehi picture Sualeh Fatehi · Oct 22, 2012

You cannot use both -jar and -cp on the command line - see the java documentation that says that if you use -jar:

the JAR file is the source of all user classes, and other user class path settings are ignored.

You could do something like this:

java -cp lib\*.jar;. myproject.MainClass

Notice the ;. in the -cp argument, to work around a Java command-line bug. Also, please note that this is the Windows version of the command. The path separator on Unix is :.