Skip to content
DeveloperMemos

Creating a Directory With a Gradle Script

Gradle, Android, Scripting1 min read

When working on an Android project, you may come across scenarios where you need to perform tasks that go beyond the capabilities of standard build scripts. One such task is creating a directory dynamically during the build process. In this article, we'll discuss how to achieve this using a Gradle script.

Prerequisites

Before we begin, make sure you have the following prerequisites set up:

  1. Android Studio or any other Android development environment.
  2. Basic knowledge of Gradle build system.

Step 1: Create a Gradle Task

To create a directory with a Gradle script, we need to define a custom Gradle task. Open your project's build.gradle file and add the following code:

1task createDirectory {
2 doLast {
3 File myDir = new File("$rootDir/my_directory")
4 if (!myDir.exists()) {
5 myDir.mkdirs()
6 println "Directory created successfully."
7 } else {
8 println "Directory already exists."
9 }
10 }
11}

In this example, we define a task named createDirectory. Inside the task's doLast closure, we use the File class to create a new directory called "my_directory" under the project's root directory. The exists() method checks if the directory already exists. If not, we use the mkdirs() method to create the directory, and a success message is printed. Otherwise, a message indicating that the directory already exists is displayed.

Step 2: Execute the Gradle Task

Now that we have defined our custom task, we need to execute it. You can trigger the task execution in various ways:

Option 1: Command Line

Open a terminal or command prompt, navigate to your project's root directory, and run the following command:

1./gradlew createDirectory

This command will execute the createDirectory task using the Gradle wrapper (gradlew). You should see the appropriate output messages indicating whether the directory was created or if it already exists.

Option 2: Android Studio

Alternatively, you can execute the task within Android Studio by following these steps:

  1. Open the Gradle sidebar on the right-hand side of Android Studio.
  2. Navigate to your project's Tasksother category.
  3. Double-click on the createDirectory task.

The task will be executed, and the output messages will be displayed in the Run console.

Wrapping Up

In this article, we explored how to create a directory using a Gradle script in Android development. By defining a custom Gradle task and executing it, you can dynamically create directories during the build process, providing flexibility and automation for your Android projects. This technique can be handy when you need to generate specific directories based on your project requirements.