Java ARchive (JAR) Files 101
If you work with Java, you have come across JARs (or Java Archives). Java SE API supports working with JAR files, and the jar tool, which is available as part of the JDK, supports all JAR-related development. Similar to the more common ZIP format, JAR is the Java way of compressing a file. Because JARs actually use the ZIP format for compression, they are compatible with other applications as well.
Compressed files are used so frequently because they download easily and require less disk space (although disk space is not a problem these days). JAR files support these fundamental ideas of compression with some other value-added features, including versioning and security. Some of the basic features are the abilities to create, update, and view JAR files. The advanced features include using the JAR files and understanding Manifest files. This article delves into the advanced features, but so as not to ignore the basics, the following section walks you through some of the basic features.
Basic JAR Commands and FeaturesType jar at the command prompt and it lists down all the available options. Here are some of the options and their descriptions:
- c: Create, indicates that a file needs to be created
- t: Table of contents
- f: File, the output will be a file
- v: Verbose, lists all the activities that the tool is performing
- m: Merge information from an external file to the manifest file (More about manifest files further in this article)
These options are the most widely used. When you use them with the jar command, they produce the desired results. For example, the following command uses a few options and creates a JAR file named <jar-file-name>, taking inputs from the <input-file(s)> argument:
jar cvf <jar-file-name> <input-file(s)>If you have the following folder structure:
|______ |___com | |__mycomp | |____demo | |___MyApplication.java |___demo |___images |___lib
Executing the command jar cvf MyApplication.jar * would result in the following output:
added manifest adding: com/(in = 0) (out= 0)(stored 0%) adding: com/mycomp/(in = 0) (out= 0)(stored 0%) adding: com/mycomp/demo/(in = 0) (out= 0)(stored 0%) adding: com/mycomp/demo/MyApplication.java(in = 0) (out= 0)(stored 0%) adding: demo/(in = 0) (out= 0)(stored 0%) adding: images/(in = 0) (out= 0)(stored 0%) adding: lib/(in = 0) (out= 0)(stored 0%)
The output is the file MyApplication.jar, which has all the folders compressed into a single file. The most important thing to notice here is the new folder created in the JAR file: META-INF, which contains a MANIFEST.MF file.
To view the contents of the JAR file, use the command jar tf MyApplication.jar. The result will be the following output:
META-INF/ META-INF/MANIFEST.MF com/ com/mycomp/ com/mycomp/demo/ com/mycomp/demo/MyApplication.java demo/ images/ lib/
To update the JAR file, you can use the command jar uf MyApplication.jar <new-file(s)>.