Java command line with external .jar

102,205

Solution 1

Concatenate each jar file argument to cp with:

; on Windows
: on Linux or Mac

e.g.

java -cp <path>\TOOLS.jar;.;<path>\jar2.jar;<path>\jar3.jar HelloWorld

on newer JVMs (6+, I think) you can also use the * to append all JARs in a directory e.g.

java -cp .;<path>\*; HelloWorld

To go a step further and create a single packaged executable see this question.

Solution 2

If you have many jar files in one folder and don't want to append them to classpath manually. You can you a .bat on windows or shell on linux.

cpappend.bat from tomcat

rem ---------------------------------------------------------------------------
rem Append to CLASSPATH
rem
rem $Id: cpappend.bat 301115 2002-08-04 18:19:43Z patrickl $
rem ---------------------------------------------------------------------------

rem Process the first argument
if ""%1"" == """" goto end
set CLASSPATH=%CLASSPATH%;%1
shift

rem Process the remaining arguments
:setArgs
if ""%1"" == """" goto doneSetArgs
set CLASSPATH=%CLASSPATH% %1
shift
goto setArgs
:doneSetArgs
:end

And another bat file which use "for" statement to append all the jar file to classpath

set CURRENT_DIR=%cd%
set CLASSPATH=.
for %%i in (%CURRENT_DIR%\lib\*.jar) do call cpappend.bat %%i
start java -Duser.dir=%CURRENT_DIR%  -cp %CLASSPATH% a.b.c.MainApp
Share:
102,205
TheFrancisOne
Author by

TheFrancisOne

Updated on August 01, 2020

Comments

  • TheFrancisOne
    TheFrancisOne over 3 years

    I develop a project using .jar to reuse code.

    So I have on .jar named TOOLS.jar, and I develop a simple application in file HelloWorld.java which refer my package TOOLS from TOOLS.jar

    I compile with this command line:

    javac -g -d C:\MyApp -cp TOOLS.jar HelloWorld.java
    

    It's successful, and when I want to execute my application I use this command (I'm in C:\MyApp folder):

    java -cp <path>\TOOLS.jar;. HelloWorld
    

    It's successful, but my question is:

    How do I execute my application when I have multiples external .jar files?

    Do I have to add each one in command with -cp option?

    Is there a way to generate only one binary file and execute it (as .exe with C programs)?

  • Paul
    Paul almost 8 years
    to me at leaast, your use of "." here was a bit confusing at first. you use them in different places in the concatenated arguments, and without an explanation it may be confusing to a reader. The "." is necessary because by default the current directory is in the classpath; but if we specify the classpath explicitly we must make sure to include the current directory explicitly.