The Java Archive Tool (JAR) Examples

Here’s the project structure.
P.S Assume you are in “/workspace/test/classes/

1. Create a jar file

-c create new archive
-v generate verbose output on standard output
-f specify archive file name
1.1 Create a Jar file which include AwtExample.class only.
jar -cvf test.jar com/mkyong/awt/AwtExample.class
1.2 Create a Jar file which include AwtExample.class and AwtExample1.class.
jar -cvf test.jar com/mkyong/awt/AwtExample.class com/mkyong/awt/AwtExample1.class
1.3 Create a Jar file which include the all classes
jar -cvf test.jar com/mkyong/awt/*.class

2. Update a jar file

-u update existing archive
2.1 Update test.jar by adding a new class AwtExample3.class
jar -uvf test.jar com/mkyong/awt/AwtExample3.class

3. Extract a jar file

-x extract named (or all) file
s from archive
3.1 Extract all files from test.jar to current location.
jar -xvf test.jar
3.2 Extract only AwtExample.class.
jar -xvf test.jar com/mkyong/awt/AwtExample.class
3.3 Extract all files from “com” folder only.
jar -xvf test.jar com
3.4 Extract all files to another folder. Oppss..jar doesn’t has option to extract files to another folder directly. The best is changed to your prefer folder and extract it from there.
mkdir newdir
cd newdir
jar -xvf /workspace/test/classes/test.jar

4. List files from a jar file

-t list table of contents for archive
4.1 List all files.
jar -tf test.jar

5. Add manifest into jar file

Read this manifest reference, you can use this manifest file to define application’s entry point, adding classpath or package version.
-m include manifest information from specified manifest file
The common use case is create a Java exe file, or executable JAR file.
5.1 Add “Main-Class” and entry point in your manifest file
Main-Class: com.mkyong.awt.AwtExample
Jar them all
jar -cvfm AwtExample.jar manifest.txt com/mkyong/awt/*.class


Popular Posts