- چگونه یک فایل JAR  در جاوا ایجاد کنیم - Developer

وبلاگ

چگونه یک فایل JAR  در جاوا ایجاد کنیم

1. مقدمه

یک کلاس جاوا می تواند در یک  jar (Java Archive) ذخیره شود.

بسیار معمول است که چندین کلاس جاوا را در یک فایل JAR  به صورت آرشیو قرار گیرد و با استفاده از جاوا آنرا اجرا کنیم.

برای این منظور کافی است مراحل زیر را انجام دهید.

 

2. Java Program Setup

Before we can create a runnable jar file, our application needs to have a class with a main method. This class provides our entry point into the application:

public static void main(String[] args) {
    System.out.println("Hello Baeldung Reader!");
}

 

3. Jar Command

Now that we're all set up let's compile our code and create our jar file.

We can do this with javac from the command line:

The javac command creates JarExample.class in the com/baeldung/jar directory. We can now package that into a jar file.

javac com/baeldung/jar/*.java

 

3.1. Using the Defaults

To create the jar file, we are going to use the jar command.

To use the jar command to create a jar file, we need to use the c option to indicate that we're creating a file and the f option to specify the file:

jar cf JarExample.jar com/baeldung/jar/*.class

 

3.2. Setting the Main Class

It's helpful for the jar file manifest to include the main class.

The manifest is a special file in a jar located the META-INF directory and named MANIFEST.MFThe manifest file contains special meta information about files within the jar file.

Some examples of what we can use a manifest file for include setting the entry point, setting version information and configuring the classpath.

 

By using the e option, we can specify our entry point, and the jar command will add it to the generated manifest file.

Let's run jar with an entry point specified:

jar cfe JarExample.jar com.baeldung.jar.JarExample com/baeldung/jar/*.class

 

3.3. Updating the Contents

Let's say we've made a change to one of our classes and recompiled it. Now, we need to update our jar file.

Let's use the jar command with the option to update its contents:

jar uf JarExample.jar com/baeldung/jar/JarExample.class

 

00

پست‌های وبلاگ بیشتر

افزودن نظرات