Objective
To cover basic concept of GRADLE to run the main method of Java program by:
- Creating an executable jar file of the project
- Run the main method using executable jar file
Why should we prefer executable Java Archive (JAR) file?
Some of the benefits of using Java Archive (JAR) file are given below.
- It can be used as library reference to include the classes.
- It is a compiled version, so the process of compiling is not required for executable JAR files.
- It is easy to run an executable JAR file.
- It is in compressed form and requires less space.
Prerequisites
Before running the Java program, you must have to configure GRADLE and JAVA on your system. Please refer the following link to configure GRADLE: http://webdemo.saksoft.com/360logica/blog/2015/11/how-to-configure-gradle-on-windows-machine.html
Write a simple JAVA program by following the given steps
1. Create a folder named as “GradleWorkspace”.
2. Open Notepad++ and write the Java code as shown in the below image.
3. Save the Java program file as “GradleDemo.java”.
Create and configure build.gradle
1. Open Notepad++
2. Go to File >> New and write the code given below.
apply plugin: ‘java’
This plugin will enable the basic Java build functionality.
3. Now we need to specify the name of the class that contains the main method. For this, add the code given below.
jar { manifest { attributes 'Main-Class': 'GradleDemo' } }
Note: If we don’t declare the name of the main method in build.gradle file, then we will get the following error while executing the jar file.
Create execuatble JAR file
1. Press “Windows + R” button and type ‘cmd’ as shown below.
2. Go to the Java file location by typing: cd E:\GradleWorkspace.
3. Enter the command “gradle build”. This command will create the executable JAR file under build/libs folder with the name of root folder (for e.g.: GradleWorkspace.jar).
Run executable JAR file
1. Go to the command prompt and reach root folder/build/libs.
2. Enter the command: java –jar <ExecutableJarFileName>.jar
3. Verify the result.