Home >Java >javaTutorial >Journey From Java file to a JAR file
This guide details the process of creating a JAR file from a Java source file. We'll cover each step with explanations and examples.
Step 1: Java Code Creation
Create a .java
file containing your Java code. For instance, a file named Main.java
might look like this:
<code class="language-java">public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }</code>
This is your source code, adhering to Java's syntax and rules.
Step 2: Compilation
Compile the .java
file using the Java compiler (javac
):
<code class="language-bash">javac Main.java</code>
This generates a .class
file (e.g., Main.class
) containing bytecode – machine-readable instructions for the Java Virtual Machine (JVM). Each .java
file produces a corresponding .class
file.
Step 3: Manifest File (Optional)
Create a MANIFEST.MF
file (optional but recommended) to define JAR metadata. For example:
<code>Main-Class: Main</code>
Main-Class
specifies the application's entry point (the class with the main
method). This simplifies JAR execution.
Step 4: JAR File Packaging
Use the jar
command to package the .class
file(s), resources, and (optionally) the manifest file into a JAR:
<code class="language-bash">jar cvfm MyApplication.jar MANIFEST.MF Main.class</code>
c
: Creates a new JAR.v
: Enables verbose output (shows the packaging process).f
: Specifies the output JAR filename (MyApplication.jar
).m
: Includes the manifest file (MANIFEST.MF
).The jar
tool creates a single, portable archive (MyApplication.jar
) containing all compiled components.
Step 5: JAR File Testing
Run the JAR file to verify its functionality:
<code class="language-bash">java -jar MyApplication.jar</code>
Successful execution should produce the output:
<code>Hello, World!</code>
The JVM uses the MANIFEST.MF
(if present) to locate the Main-Class
and execute its main
method.
Step 6: JAR File Deployment
Deployment depends on the target environment:
java -jar
.java -jar
.<code class="language-dockerfile">FROM openjdk:17 COPY MyApplication.jar /app/MyApplication.jar WORKDIR /app CMD ["java", "-jar", "MyApplication.jar"]</code>
Build (docker build -t my-java-app .
) and run (docker run -p 8080:8080 my-java-app
) the container.
Execution Summary:
.java
)..class
files using javac
.MANIFEST.MF
.jar
.java -jar
.The above is the detailed content of Journey From Java file to a JAR file. For more information, please follow other related articles on the PHP Chinese website!