Chris Tei
Chris Tei

Reputation: 316

Setting the Resource Folder in a Java Gradle project

I am trying to set up a Gradle Java project, but for some reason I can't seem to register the resources folder with the build. Whenever I try to write to a file, it writes to the project root and not the resources folder.

My project directory is as follows:

Here is my build.gradle file

apply plugin: 'java'
apply plugin: 'application'

repositories {
        mavenCentral()
}

mainClassName='Test'


sourceSets {
        main {
                java {
                        srcDirs= ["src/main/java"]
                }
                resources {
                        srcDirs= ["src/main/resources"]
                }
        }
}

And here is my Test.java that I'm using to see if I can access the resources folder

import java.io.*;

public class Test {

        public static void main(String[] args) throws Exception {

                FileWriter writer = new FileWriter(new File("Test.txt"));
                writer.write("Test");
                writer.close();

        }

}

Upvotes: 16

Views: 44965

Answers (1)

Jose Martinez
Jose Martinez

Reputation: 12022

Your current directory can be retrieved from the system property user.dir. E.g. System.getProperty("user.dir").

The resources directory is not the same as the working directory, which is the directory that your application executed from. The resource directory is used mainly for storing files that were created before runtime, so that they can be accessed during runtime. It is not meant to be written to during runtime. So that's why when you set the resource path in Gradle it is not going to set your current working directory to the resource path.

You can still do what you want to do, but you will have to write to ./src/main/resources/Test.txt. I know that sometimes while you are developing your application you would want to be able to write to the resource folder. But just note that when the application is running in the wild, it is not expected that you will be writing to the resource folder, especially since more often than not it will be inside a JAR file.

Upvotes: 7

Related Questions