Continuing our gradle tutorials, we will see how we can use inbuilt functions to achieve our targets. Gradle can have build scripts. While building projects, we may need to copy a set of files into some other folder to match with our deployment or project structure. Instead of manually doing this task, we can write build script which uses gradle copy task.
Gradle Copy Task
Gradle copy task provides the functionality to copy files from source to destination using build scripts. You can write a task in script and invoke it. It will copy the files as per our instructions. Create a project called CopyTask which has the folder structure as below.
Now you want to write a build script which copies all files and folders from src/main/files into build/target/content. We want to exclude all text files in root folder but want to copy all files in subfolders. We can achieve this using gradle copy task. Let us write the build script required for it.
We have defined a task called copyFiles. Observe following things from it.
- from specifies the directory from which files should be copied.
- exclude specifies that .txt files should not be copied from specified directory
- into denotes the target directory in which files are to be copied.
These all are methods of gradle copy task of which official documentation can be found on official gradle website.
Simply call copyFiles task from command line which will invoke gradle copy task. Run command gradle copyFiles from the location of your build.gradle. The build will be successful and it will create a folder structure build/target/content. It is as below.