Java applications are typically delivered as JAR (short for Java Archive) files.
Not all JAR files are executable. Some may be just a library that you use in your own application.
While some executable JAR files can be launched simply by double-clicking, the fool-proof way to run a jar file is to
use the java -jar
. For example, if the foo.jar
is in C:\projects
folder, you can do the following:
C:\projects
folder using the cd
command (e.g., cd C:\projects
)java -jar foo.jar
.Would like to try the above yourself? Download the Collate-TUI.jar from https://se-edu.github.io/collate/ and run it using the commandjava -jar Collate-TUI.jar
command. The JAR file's usage is given here.
A normal JAR file contains only the classes and resources that you created for your app. If your app has dependencies (i.e., third party libraries that your app depends on), the JAR file will not work unless the person running the JAR file also has those dependencies in their computer. This is not ideal.
A fat JAR (aka uber JAR) file solves the above problem by including all the dependencies inside the JAR file itself (which makes the JAR file bigger than usual, hence the term fat).
If you are using Gradle in your project, you can use the Shadow Gradle plugin to package an application into an executable JAR file. It is particularly useful if you wish to create a fat JAR file.
To use the Shadow plugin, first ensure the following plugins are listed in your build.gradle
file.
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '7.1.2'
// other plugins
}
Second, ensure the following property is configured correctly, so that Shadow know which class is the entry point to the application:
mainClassName = 'seedu.duke.Main'
The task shadowJar
(e.g., running the command gradlew shadowJar
or gradlew clean shadowJar
) creates a JAR file with the name in the format of {archiveBaseName}-{archiveVersion}.jar
and puts it in the builds/libs
folder. This output file name/location can be tweaked further using the properties destinationDir
, archiveBaseName
, archiveVersion
in the build.gradle
file. e.g.,
shadowJar {
archiveFileName = 'duke.jar'
}
If you are using JavaFX, see the panel below to find what else you need to add to the build.gradle
to pack JavaFX libraries into the generated JAR file.
Creating a JAR file in Intellij - A video by Artur Spirin:
If your app uses third-party libraries, you are recommended to create a fat JAR file using Gradle instead.
Although JUnit is a third-party library, you need not package it into a fat JAR file because JUnit is used only in the test code, not in the application code.
But if you use JavaFX, you need to package the JavaFX libraries into a fat JAR file.