Saturday, May 23, 2009

Add multiple jars to classpath

In java (in UNIX like platform), it is not enough just to include the directory, in which the jar dependencies of your application reside, to the classpath. It is required to include path of each and every dependant jars to the classpath. If your application only depends on few jars this is not a problem. But, what if your application depends on several jars say 20, it will be an annoying task to add all the paths of jars to the classpath manually.
It is possible to use a simple shell script to accomplish the above mentioned task. The script can be customized to suit your application very easily.


export JAR_HOME=path to directory which includes jars

for f in $JAR_HOME/*.jar

do

JAR_CLASSPATH=$JAR_
CLASSPATH:$f
done

export JAR_CLASSPATH


#the next line will print the JAR_CLASSPATH to the shell.
echo the classpath $JAR_CLASSPATH


java -classpath $JAR_CLASSPATH Name of the programme

Say your jars are in several diferent folders, then you will have to use a for loop per each directory and finally concaternate to a single variable.

4 comments:

  1. Good tip Waruna, pretty useful. I have also shared few thoughts on my blog post How Classpath works in Java, let me know how do you find it.

    ReplyDelete
  2. it was very helpful.
    Thank you so much

    ReplyDelete
  3. thanks, but the result includes a wrong ':' character just after -classpath
    it causes an error:

    -classpath :./libjars/commons-codec-1.2.jar:./libj...

    -classpath ":" + ./libjars/commons-codec-1.2.jar:./libj....

    Any idea?
    thanks.

    ReplyDelete
  4. Check how to update classpath to include jar file in java at Modern Pathshala

    ReplyDelete