Java to create JAR file included with jar libraries

Java to create JAR file included with jar libraries

A JAR file is still a .zip file, but includes a special manifest file to identify its contents.

Suppose you have the directory structure with several .class files and images directory and some libraries used in your project. You could use the jar utility to put all these into a new JAR file which you can name it of your projectname.jar

The general format for the jar command is

jar options filenames

The first file named in the filenames list is the name of the archive.

You can study options through command.

jar -h

Basically its an help command..

Creating an jar archive:

In order to make new archive, then use

jar cf YourJar.jar *.class images/*.png lib/*.jar

If you had prepared a manifest file called MANIFEST.MF then

jar cfm YourJar.jar MANIFEST.MF *.class images/*.png lib/*.jar

Adding libraries into your classpath

Let us consider your project contains mysql-connector.jar , mail.jar and activation.jar libraries, and images and some other packages with class file for example

C:/YourProject

|

|—MANIFEST.MF

|—package

| |—mainclass.java

| |—aclass.java

|—anotherpackage

| |—bclass.java

| |—cclass.java

|—images

| |—icon.png

| |—pic.png

|—lib

| |—mysql-connector.jar

| |—mail.jar

| |—activation.jar

Now you want to put all these files and folders into an jar archieve,

First, you need to create a MANIFEST.MF file, with text editor add these lines

Manifest-Version: 1.0

Created-By: Harish Manohar

Class-Path: lib/mysql-connector.jar lib/mail.jar activation.jar

Main-Class: package.mainclass

Now Compile your java files using javac command

and if you to add all your source files and class files, you can use

jar cfm Myproject.jar MANIFEST.MF -C c:/YourProject/ .

Note: it will store all your files under YourProject folder including java files.

If you want to add only class files.,then navigate to your project folder using cd command, then type

jar cfm Myproject.jar MANIFEST.MF package/*.class anotherpackage/*.class images/*.png lib/*.jar

Now execute the jar using command

java -jar Myproject.jar

All done., Hope it will be useful to you in any way.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s