JAR file using Java commands

Following are few commands that can be used to create/view/modify/execute a JAR file using Java command line utilities and JVM.

Create a JAR file

1
2
3
jar cf JAR_FILE_NAME FILE_NAMES_OR_DIRECTORY_NAME
e.g.
jar cf MyApp1.jar C:\JavaProject\MyApp

View contents of a JAR file

1
2
3
jar tf JAR_FILE_NAME
e.g.
jar tf MyApp1.jar

View contents with detail of a JAR file

1
2
3
jar tvf JAR_FILE_NAME
e.g.
jar tvf MyApp1.jar

Note that we have used v (verbose) option to see the detail of JAR.

Extract content of JAR file

1
2
3
jar xf JAR_FILE_NAME
e.g.
jar xf MyApp1.jar

Extract specific file from JAR file

1
2
3
jar xf JAR_FILE_NAME FILE_NAME(S)_FROM_JAR_FILE
e.g.
jar xf MyApp1.jar Test1.class

Update a JAR file

1
2
3
jar uf JAR_FILE_NAME FILE_NAMES_FROM_JAR_FILE
e.g.
jar uf MyApp1.jar Test1.class

Executing a JAR file

1
2
3
java -jar JAR_FILE_NAME
e.g.
java -jar MyApp.jar

Create an executable JAR file

In order to create an executable JAR, one of the classes that we include in our JAR must be a main class.
Create a text file called MANIFEST.MF using any text editor and copy following content in it.

1
2
Manifest-Version: 1.0
Main-Class: MyMainClass

Where MyMainClass is the name of the class that contents main method. Also note that you have to specify fully qualified class name here.
Use following command to create an executable JAR file.

1
jar cvfm MyApp.jar MANIFEST.MF FILE_NAMES_OR_DIRECTORY_NAME

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