Compiling Jars
To compile Java files into a JAR file, follow these steps:
1. Compile Java Files into .class Files
Run this in the terminal (assuming your Java files are in the src directory):
javac -d out src/*.java
-d outplaces compiled.classfiles into theoutdirectory.src/*.javacompiles all Java files insrc.
2. Create a Manifest File (Optional, for Executable JARs)
Create a manifest.txt file specifying the entry point (if applicable):
Main-Class: com.example.Main
(Replace com.example.Main with your actual main class.)
3. Package Everything into a JAR
Run the following command:
jar cfm app.jar manifest.txt -C out .
c→ Create a JAR.f→ Specifies the output file (app.jar).m→ Uses themanifest.txtfile.-C out .→ Adds compiled files from theoutdirectory.
4. Run the JAR File
If it's an executable JAR:
java -jar app.jar
Alternative: Without Manifest
If you don’t need an executable JAR (e.g., it's a library):
jar cf app.jar -C out .
This just creates a JAR of compiled classes without an entry point.
Automation Using Gradle or Maven
If you're using Gradle, add this to build.gradle:
jar {
manifest {
attributes 'Main-Class': 'com.example.Main'
}
}
Then build it with:
gradle jar
If you're using Maven, package with:
mvn package
That’s it! 🚀 Now you have a .jar file ready to use.