Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • src
    • main
      • java
      • resources

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();

        }

}
like image 915
Chris Tei Avatar asked Dec 24 '16 17:12

Chris Tei


1 Answers

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.

like image 128
Jose Martinez Avatar answered Sep 25 '22 16:09

Jose Martinez