Archive for the ‘JAR’ Category

Setting up classpath from jar file

May 27, 2010 Leave a comment

Jar files (JAva aRchives) are very convenient containers, you can pack all you need for your application (at least for classes and resources), put the jar on the target environment and just run java -cp <myapp.jar> <appMain> <command line args> to execute your program.

With a jar file you don’t need scripts or long command line to setup your classpath for execution.  Nevertheless if you can do better than configuring the classpath and the main from command line, you can use the manifest file for this. Doing so, you can just type java -jar <command line args>

The manifest is a text file (property like) containing information on the archive, as part of this information you can define the main class of the archive and define the classpath (as long you did not pack other jar too)

In order to do so, define in the manifest the following tag ‘Class-Path’ and ‘Main-Class’. Following is a sample:

Main-Class: sample.package.MyMain
Class-Path: directory-one/sub-directory-one/referenced.jar directory-two/

Keep in mind that:

  1. You specify several directories and/or referenced jar using a space as delimiter
  2. Reference to directories and other jars are relative to the jar
  3. Any referenced jar using the Class-Path attribute cannot be present in your original archive (without special classloader)
  4. If you have resource in some directory don’t forget the slash at the end otherwise the content of the directory is not seen.


JAR specification

Categories: JAR, Java Tags: , ,