Creating a Java CLASSPATH dynamically from jars in a directory
When creating DOS batch file to launch a Java application, many people build the classpath by hand. For example:
This is kind of a pain. Especially, when working on an evolving project where the jars change relatively frequently. It would be much easier if the batch file built the classpath dynamically based on the jars found in a directory. Here's how to do this:
First, here's the directory layout for our imaginary application. I'm just explaing this so that you aware of how this example is structured.
APP_HOME |~~ bin (Batch files live here) `~~ lib (Jars live here)Next, create a batch file to launch your Java application or to setup your environment. It's contents will look something like:
@echo off REM $Id: $ REM Setup the APP environment REM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ REM APP_HOME assumes that your batch file is in APP_HOME\bin. REM If your batch file is in APP_HOME change the next line REM to 'SET APP_HOME=%~dp0' SET APP_HOME=%~dp0.. SET APP_LIB=%APP_HOME%\lib SET APP_CLASSPATH= FOR %%i IN ("%APP_LIB%\*.jar") DO CALL cpappend.bat %%iNotice the call to cpappend.bat. You need to create that batch file; it's contents are:
REM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ REM Append to APP_CLASSPATH REM REM $Id: $ REM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SET _TEMP= REM Process the first argument IF ""%1"" == """" GOTO end SET _TEMP=%1 SHIFT REM Process the remaining arguments. REM Paths with spaces are handled here :setArgs IF ""%1"" == """" GOTO doneSetArgs SET _TEMP=%_TEMP% %1 SHIFT GOTO setArgs REM Build the classpath :doneSetArgs SET APP_CLASSPATH=%APP_CLASSPATH%;"%_TEMP%" GOTO end :endIf you're working on Mac OS X, Linux, or UNIX setting the path dynamically is much simpler. Here's the equivalent shell scripting code:
APP_HOME=`dirname "$0"`/.. APP_LIB= $APP_HOME/lib APP_CLASSPATH= for jar in $(ls $APP_LIB/*.jar) do APP_CLASSPATH=$APP_CLASSPATH:$jar done