How to creating a JAR? – it’s easy.
Creating a JAR file in Java involves compiling your Java source code and then packaging the compiled .class
files, along with any resources, into a single archive. Here’s a step-by-step guide on how to do it.
1. Compile Your Java Code
Before creating a JAR file, you need to compile your Java source code. This generates the .class
files that will go into the JAR.
Command to Compile Java Files:
complile…
javac MyProgram.java
This will create MyProgram.class
.
2. Create a Manifest File (Optional but recommended for Executable JARs)
The manifest file (MANIFEST.MF
) is an optional file that can specify various metadata about the JAR, such as the entry point (the class with the main()
method). If you’re creating an executable JAR, you must specify the Main-Class
in the manifest.
Example manifest.txt
:
making file
Manifest-Version: 1.0 Main-Class: com.example.Main
Where com.example.Main
is the fully qualified name of the class containing your main
method.
3. Create the JAR File
Now, use the jar
command to create the JAR file. The basic syntax is:
Command to Create a JAR:
command
jar cfm MyApp.jar manifest.txt *.class
c
– create a new JAR file.f
– specify the output file name (MyApp.jar
).m
– include the manifest file (manifest.txt
).*.class
– includes all compiled.class
files.
If you’re creating a library JAR (non-executable), you can omit the manifest.txt
:
command
jar cf MyLibrary.jar *.class
4. Add Other Files (Optional)
You can also include other resources like images, configuration files, or libraries when creating the JAR. For example:
command
jar cfm MyApp.jar manifest.txt *.class resources/*.png config.properties
5. Running the JAR (For Executable JARs)
Once the JAR file is created, you can run it (if it’s executable) using the java -jar
command:
command
java -jar MyApp.jar
Example:
1. Java source file (HelloWorld.java
):
java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2. Compile the Java file:
command
javac HelloWorld.java
3. Create a manifest.txt
file:
making file…
Manifest-Version: 1.0 Main-Class: HelloWorld
Create the JAR file:
creating…
jar cfm HelloWorld.jar manifest.txt HelloWorld.class
Run the JAR file:
running…
java -jar HelloWorld.jar
Popular post
-
Eclipse IDE – Create New Java Project.
Opening the New Java Project…
-
How to start the project in android studio
Android Studio Open the Android…
-
How to use ACOSH function in excel
The ACOSH function returns the…
-
Complete Header tags in html – easy to learn
H tags can be used…
-
Best features in Python programme – easy to learn
Python is the most widely…