Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute jar file with multiple classpath libraries from command prompt

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?

like image 580
Praneeth Avatar asked Oct 22 '12 19:10

Praneeth


People also ask

How do I put all JARs in a folder classpath?

In general, to include all of the JARs in a given directory, you can use the wildcard * (not *. jar ). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.


1 Answers

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 :.

like image 106
Sualeh Fatehi Avatar answered Oct 12 '22 07:10

Sualeh Fatehi