In Linux, how to execute Java jar file with external jar files?

14,575

Solution 1

Either use the -cp flag:

java -cp /path/to/somefolder/*.jar:/path/to/otherfolder/*.jar com.YourMainClass

Or add a Class-Path: header to your jar's manifest (see Jigar's answer)


Note to others who answered with java -jar <etc>: The -jar flag deactivates the standard -cp flag and CLASSPATH environment variable, because it retrieves the classpath from the JAR manifest. Any answer that combines -jar and either -cp or $CLASSPATH will not work.

This information is well-hidden, but I finally found a reference:

-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests. When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

Source: java - the Java application launcher

Solution 2

java -jar /path/to/externalJarFile.jar

Update

You can add the required library in manifest with Class-Path: header

For example :

Class-Path: MyUtils.jar

See

Share:
14,575

Related videos on Youtube

Gowtham
Author by

Gowtham

Updated on June 04, 2022

Comments

  • Gowtham
    Gowtham almost 2 years

    In Linux, how to execute Java jar file with external jar files?

  • Gowtham
    Gowtham about 13 years
    for example i want to execute sample.jar file.but its required additional jar files(say add.jar) located with differnt path.Now how to execute sample.jar
  • Sean Patrick Floyd
    Sean Patrick Floyd about 13 years
    This is the first correct answer here that features the -jar flag (+1)