Create your Java JAR using the command line
This is the simplest way to create a Java JAR (Java Archive), ie, an executable Java program.
1. Prerequiste
- OpenJDK 11
- Bash or ZSH
- Git
2. Hands on
Creating a project using git, yes, is a good practice to track your code.
git init my-executable
and then cd my-executable
to access the project directory.
Add a new file, ie, a class and add some content.
touch MyExecutable.java && vi MyExecutable.java
Add the content below to the class
import java.time.LocalDateTime;
public class MyExecutable {
public static void main(String... args) {
System.out.println("Hello there at "+LocalDateTime.now());
}
}
Compile the class and then run it. The output should be `Hello there at YYYY–MM–DDTHH:mm:ss.zzzz`
javac *.java && java MyExecutable
Copy the command below to generate the jar. The arguments mean: Using the jar program, create a new jar named MyExecutable.jar, add MyExecutable as entry point class, and add the MyExecutable.class inside the jar.
jar cfe MyExecutable.jar MyExecutable MyExecutable.class
To execute the jar, run the command
java -jar MyExecutable.jar
3. Commit the code
As a good practice, always track your code, to be able to recover or review it.
Before you continue, let’s check the status using git status
command
The class and JAR files are files generated and don’t need to be tracked at this time. Let’s ignore them.
3.1 .gitignore
Let’s ignore some of the files mentioned above. First, creating a .gitignore file and then adding the files to be skipped.
touch .gitignore && vi .gitignore
3.2 Add the class
Now using the command git status
again, the Java class and the new file .gitignore are available to be tracked.
Add to track and then commit them.
git add .
git commit -m 'My first executable Jar'
That’s it 🙏