Gradle Quick Guide: Creating a Java Project

Quickly create a Java project with Gradle.

Development Environment

  • Java: 1.8
  • Gradle: 4.1

Create a Gradle Project

Create the gradle-hello-world directory and initialize a Gradle project.

$ mkdir gradle-hello-world
$ cd gradle-hello-world/
$ gradle init

BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed

Write Source Code

Create the source code directory.

$ mkdir -p src/main/java/hello

Write the source code file src/main/java/hello/HelloWorld.java.

package hello;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("hello world!");
  }
}

Build with Gradle

Add the following content to build.gradle for the build.

apply plugin: 'java'

NOTE: All build-related content is written in build.gradle.

When you build with the gradle build command, Gradle creates the build directory and builds the source code.

$ gradle build

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed

Run the Gradle Project with gradlew

Add the following content to the build.gradle file to run the application directly.

apply plugin: 'application'
mainClassName = 'hello.HelloWorld'

Run the application directly with the gradlew run command.

$ ./gradlew run

> Task :run
hello world!


BUILD SUCCESSFUL in 2s
2 actionable tasks: 1 executed, 1 up-to-date

Directory Structure

Enter tree to check the created directory structure.

$ tree
.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    └── main
        └── java
            └── hello
                └── HelloWorld.java

Source Code

Reference