Run Your First Java App · Lesson 7/12
58%
⏱ 10–15 min

How to Create and Use JAR Files in Java

For convenient application distribution, Java provides a mechanism called JAR (Java Archive) files. JAR files are used for archiving and compressing data.

Basic command format for creating a JAR file is as follows:

jar -cf jar-file input-file(s)

The generated JAR file will be placed in the current directory.

Let's examine the keys and arguments used in this command:

  • The flag c indicates that a JAR file should be created.
  • The flag f specifies that the output should be directed to a file rather than standard output.
  • jar-file is the name to be assigned to the resulting JAR file. You can use any name for the JAR file. By convention, the JAR file name is given a .jar extension, though this is not mandatory.
  • The argument input-file(s) is a space-separated list of one or more files you want to include in your JAR file. The input-file(s) argument may also contain a wildcard *. If any of the input files are directories, their contents are recursively added to the JAR archive.

Rules regarding JAR file structure

  • The jar command automatically creates the META-INF directory.
  • The jar command automatically generates the MANIFEST.MF file and places it in the META-INF directory.
  • The exact directory structure is preserved.
  • The java and javac commands can use a JAR file just like a normal directory tree.
  • Searching for JAR files using the -cp flag is similar to searching for package files. The only difference is that the path to the JAR file must include the JAR file name (e.g., classes/project1.jar).

Let's see an example of how JAR files are created and used.

Suppose our application has the following directory structure:

Directory structure photo

We will create a JAR file named project1.jar, which will contain the first and second packages:

cd project1/classes
jar –cf project1.jar first second

We can view the contents of the project1.jar file using the following command:

jar -tf project1.jar

The output will be approximately as follows:

META-INF/
META-INF/MANIFEST.MF
first/
first/Example1.class
second/
second/Example2.class

Now, we will move the created project1.jar file to the lib directory and run the first.Example1 program:

cd lib
java -cp project1.jar first.Example1

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. OOP Basics
9. Lambda Expressions
10. Stream API
11. Inner Classes and Exceptions
12. Git & GitHub
‹ Previous lesson Next lesson ›