Home > Java > javaTutorial > body text

How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?

Mary-Kate Olsen
Release: 2024-11-08 03:04:02
Original
944 people have browsed it

How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?

Call "java -jar MyFile.jar" with Additional Classpath Option

In Java, there are two ways to execute a JAR file: using the -jar option or specifying the classpath with -cp. However, attempting to combine both options leads to an error.

When using -jar, the Java Virtual Machine (JVM) assumes that the JAR file contains all necessary dependencies. Therefore, specifying an additional classpath with -cp is not recommended.

Instead, there are two alternative approaches:

Approach 1: Add JARs to the Main Manifest

  1. Copy the required JAR files to a subfolder, such as "libs".
  2. Use the task in Ant before building the JAR:
<code class="xml"><manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar">
  <classpath>
    <fileset dir="libs" includes="*.jar" />
  </classpath>
</manifestclasspath></code>
Copy after login
  1. Create the JAR with the updated manifest:
<code class="xml"><jar destfile="MyProgram.jar" basedir="classes">
  <manifest>
    <attribute name="Main-Class" value="main.Main" />
    <attribute name="Class-Path" value="${myprogram.manifest.classpath}" />
  </manifest>
</jar></code>
Copy after login

By specifying the classpath in the manifest, java -jar MyProgram.jar will include all the dependencies.

Approach 2: Specify Classpath with -cp

  1. Include all required JAR files in the classpath:
java -cp 'MyProgram.jar:libs/*' main.Main
Copy after login

Using the * syntax expands to include all JAR files in the "libs" directory.

Remember, it is crucial to choose either the -jar or -cp approach. Combining both can lead to classpath conflicts and errors.

The above is the detailed content of How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!